Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
36.76% covered (danger)
36.76%
988 / 2688
5.66% covered (danger)
5.66%
3 / 53
CRAP
0.00% covered (danger)
0.00%
0 / 1
AppController
36.71% covered (danger)
36.71%
986 / 2686
5.66% covered (danger)
5.66%
3 / 53
213176.35
0.00% covered (danger)
0.00%
0 / 1
 processSGF
73.58% covered (warning)
73.58%
39 / 53
0.00% covered (danger)
0.00%
0 / 1
19.15
 xFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 yFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getInitialPositionEnd
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
3.47
 getInitialPosition
50.00% covered (danger)
50.00%
10 / 20
0.00% covered (danger)
0.00%
0 / 1
10.50
 getInvisibleSets
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getDeletedSets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 startPageUpdate
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 uotd
0.00% covered (danger)
0.00%
0 / 157
0.00% covered (danger)
0.00%
0 / 1
2070
 deleteUnusedStatuses
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
72
 saveSolvedNumber
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
156
 convertEloToXp
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 resetUserElos
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 getNewElo
58.23% covered (warning)
58.23%
46 / 79
0.00% covered (danger)
0.00%
0 / 1
57.28
 handleContribution
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
2.42
 getAllTags
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 deleteUserBoards
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 halfXP
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 getNewTsumego
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 publishSingle
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
30
 getTsumegoOfTheDay
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 1
1190
 ratingMatch
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
992
 rating2
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 encrypt
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 decrypt
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 checkPictureLarge
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 checkPicture
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 getTsumegoRankx
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
506
 adjustElo
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
132
 getTsumegoElo
60.38% covered (warning)
60.38%
32 / 53
0.00% covered (danger)
0.00%
0 / 1
95.70
 getTsumegoRankVal
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 getTsumegoRankMax
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 saveDanSolveCondition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 updateSprintCondition
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
4.00
 updateGoldenCondition
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 setPotionCondition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 updateGems
3.85% covered (danger)
3.85%
4 / 104
0.00% covered (danger)
0.00%
0 / 1
2183.48
 checkProblemNumberAchievements
42.39% covered (danger)
42.39%
39 / 92
0.00% covered (danger)
0.00%
0 / 1
166.38
 checkDanSolveAchievements
54.91% covered (warning)
54.91%
95 / 173
0.00% covered (danger)
0.00%
0 / 1
354.78
 checkForLocked
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 checkNoErrorAchievements
81.54% covered (warning)
81.54%
53 / 65
0.00% covered (danger)
0.00%
0 / 1
18.82
 checkTimeModeAchievements
35.40% covered (danger)
35.40%
40 / 113
0.00% covered (danger)
0.00%
0 / 1
2273.83
 checkRatingAchievements
54.44% covered (warning)
54.44%
49 / 90
0.00% covered (danger)
0.00%
0 / 1
95.92
 checkLevelAchievements
72.22% covered (warning)
72.22%
65 / 90
0.00% covered (danger)
0.00%
0 / 1
42.63
 checkSetCompletedAchievements
19.72% covered (danger)
19.72%
14 / 71
0.00% covered (danger)
0.00%
0 / 1
166.54
 setAchievementSpecial
0.00% covered (danger)
0.00%
0 / 184
0.00% covered (danger)
0.00%
0 / 1
4160
 checkSetAchievements
18.10% covered (danger)
18.10%
40 / 221
0.00% covered (danger)
0.00%
0 / 1
2533.09
 getXPJump
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 updateXP
75.00% covered (warning)
75.00%
36 / 48
0.00% covered (danger)
0.00%
0 / 1
18.52
 getPartitionRange
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
56
 handleSearchSettings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 signIn
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 beforeFilter
83.58% covered (warning)
83.58%
280 / 335
0.00% covered (danger)
0.00%
0 / 1
93.31
 afterFilter
n/a
0 / 0
n/a
0 / 0
1
1<?php
2
3App::uses('Auth', 'Utility');
4App::uses('TsumegoFilters', 'Utility');
5
6class AppController extends Controller {
7    public $viewClass = 'App';
8
9    public $components = [
10        'Session',
11        //'DebugKit.Toolbar',
12        'Flash',
13        'PlayResultProcessor',
14        'TimeMode',
15    ];
16
17    public static function processSGF($sgf) {
18        $aw = strpos($sgf, 'AW');
19        $ab = strpos($sgf, 'AB');
20        $boardSizePos = strpos($sgf, 'SZ');
21        $boardSize = 19;
22        $sgfArr = str_split($sgf);
23        if ($boardSizePos !== false) {
24            $boardSize = $sgfArr[$boardSizePos + 3] . '' . $sgfArr[$boardSizePos + 4];
25        }
26        if (substr($boardSize, 1) == ']') {
27            $boardSize = substr($boardSize, 0, 1);
28        }
29
30        $black = AppController::getInitialPosition($ab, $sgfArr, 'x');
31        $white = AppController::getInitialPosition($aw, $sgfArr, 'o');
32        $stones = array_merge($black, $white);
33
34        $board = [];
35        for ($i = 0; $i < 19; $i++) {
36            $board[$i] = [];
37            for ($j = 0; $j < 19; $j++) {
38                $board[$i][$j] = '-';
39            }
40        }
41        $lowestX = 18;
42        $lowestY = 18;
43        $highestX = 0;
44        $highestY = 0;
45        $stonesCount = count($stones);
46        for ($i = 0; $i < $stonesCount; $i++) {
47            if ($stones[$i][0] < $lowestX) {
48                $lowestX = $stones[$i][0];
49            }
50            if ($stones[$i][0] > $highestX) {
51                $highestX = $stones[$i][0];
52            }
53            if ($stones[$i][1] < $lowestY) {
54                $lowestY = $stones[$i][1];
55            }
56            if ($stones[$i][1] > $highestY) {
57                $highestY = $stones[$i][1];
58            }
59        }
60        if (18 - $lowestX < $lowestX) {
61            $stones = AppController::xFlip($stones);
62        }
63        if (18 - $lowestY < $lowestY) {
64            $stones = AppController::yFlip($stones);
65        }
66        $highestX = 0;
67        $highestY = 0;
68        $stonesCount = count($stones);
69        for ($i = 0; $i < $stonesCount; $i++) {
70            if ($stones[$i][0] > $highestX) {
71                $highestX = $stones[$i][0];
72            }
73            if ($stones[$i][1] > $highestY) {
74                $highestY = $stones[$i][1];
75            }
76            $board[$stones[$i][0]][$stones[$i][1]] = $stones[$i][2];
77        }
78        $tInfo = [];
79        $tInfo[0] = $highestX;
80        $tInfo[1] = $highestY;
81        $arr = [];
82        $arr[0] = $board;
83        $arr[1] = $stones;
84        $arr[2] = $tInfo;
85        $arr[3] = $boardSize;
86
87        return $arr;
88    }
89
90    public static function xFlip($stones) {
91        $stonesCount = count($stones);
92        for ($i = 0; $i < $stonesCount; $i++) {
93            $stones[$i][0] = 18 - $stones[$i][0];
94        }
95
96        return $stones;
97    }
98
99    public static function yFlip($stones) {
100        $stonesCount = count($stones);
101        for ($i = 0; $i < $stonesCount; $i++) {
102            $stones[$i][1] = 18 - $stones[$i][1];
103        }
104
105        return $stones;
106    }
107
108    public static function getInitialPositionEnd($pos, $sgfArr) {
109        $endCondition = 0;
110        $currentPos1 = $pos + 2;
111        $currentPos2 = $pos + 5;
112        while ($sgfArr[$currentPos1] == '[' && $sgfArr[$currentPos2] == ']') {
113            $endCondition = $currentPos2;
114            $currentPos1 += 4;
115            $currentPos2 += 4;
116        }
117
118        return $endCondition;
119    }
120
121    public static function getInitialPosition($pos, $sgfArr, $color) {
122        $arr = [];
123        $end = AppController::getInitialPositionEnd($pos, $sgfArr);
124        for ($i = $pos + 2; $i < $end; $i++) {
125            if ($sgfArr[$i] != '[' && $sgfArr[$i] != ']') {
126                array_push($arr, strtolower($sgfArr[$i]));
127            }
128        }
129        $alphabet = array_flip(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']);
130        $xy = true;
131        $arr2 = [];
132        $c = 0;
133        $arrCount = count($arr);
134        for ($i = 0; $i < $arrCount; $i++) {
135            $arr[$i] = $alphabet[$arr[$i]];
136            if ($xy) {
137                $arr2[$c] = [];
138                $arr2[$c][0] = $arr[$i];
139            } else {
140                $arr2[$c][1] = $arr[$i];
141                $arr2[$c][2] = $color;
142                $c++;
143            }
144            $xy = !$xy;
145        }
146
147        return $arr2;
148    }
149
150    protected function getInvisibleSets() {
151        $this->loadModel('Set');
152        $invisibleSets = [];
153        $in = $this->Set->find('all', ['conditions' => ['public' => 0]]);
154        if (!$in) {
155            $in = [];
156        }
157        foreach ($in as $item) {
158            $invisibleSets[] = $item['Set']['id'];
159        }
160
161        return $invisibleSets;
162    }
163
164    protected function getDeletedSets() {
165        $dSets = [];
166        $de = $this->Set->find('all', ['conditions' => ['public' => -1]]);
167        if (!$de) {
168            $de = [];
169        }
170        foreach ($de as $item) {
171            $dSets[] = $item['Set']['id'];
172        }
173
174        return $dSets;
175    }
176
177    /**
178     * @return void
179     */
180    public static function startPageUpdate() {
181        $str = '';
182        $latest = ClassRegistry::init('AchievementStatus')->find('all', ['limit' => 7, 'order' => 'created DESC']);
183        if (!$latest) {
184            $latest = [];
185        }
186        $latestCount = count($latest);
187        for ($i = 0; $i < $latestCount; $i++) {
188            $a = ClassRegistry::init('Achievement')->findById($latest[$i]['AchievementStatus']['achievement_id']);
189            $u = ClassRegistry::init('User')->findById($latest[$i]['AchievementStatus']['user_id']);
190            if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
191                $startPageUser = AppController::checkPicture($u);
192            } else {
193                $startPageUser = $u['User']['name'];
194            }
195            $latest[$i]['AchievementStatus']['name'] = $a['Achievement']['name'];
196            $latest[$i]['AchievementStatus']['color'] = $a['Achievement']['color'];
197            $latest[$i]['AchievementStatus']['image'] = $a['Achievement']['image'];
198            $latest[$i]['AchievementStatus']['user'] = $startPageUser;
199            $str .= '<div class="quote1"><div class="quote1a"><a href="/achievements/view/' . $a['Achievement']['id'] . '"><img src="/img/' . $a['Achievement']['image'] . '.png" width="34px"></a></div>';
200            $str .= '<div class="quote1b">Achievement gained by ' . $startPageUser . ':<br><div class=""><b>' . $a['Achievement']['name'] . '</b></div></div></div>';
201        }
202        file_put_contents('mainPageAjax.txt', $str);
203    }
204
205    /**
206     * @return void
207     */
208    protected function uotd() { //routine1
209        $this->loadModel('User');
210        $this->loadModel('DayRecord');
211        $this->loadModel('TsumegoAttempt');
212        $this->loadModel('Achievement');
213        $this->loadModel('AchievementCondition');
214        $today = date('Y-m-d');
215        $ux2 = $this->User->find('all', [
216            'limit' => '8',
217            'order' => 'reuse3 DESC',
218            'conditions' => [
219                'NOT' => ['id' => [33]],
220            ],
221        ]);
222        if (!$ux2) {
223            $ux2 = [];
224        }
225        $last = $this->DayRecord->find('all', ['limit' => '7', 'order' => 'date DESC']);
226        if (!$last) {
227            $last = [];
228        }
229        $lastUotds = [];
230        $lastUsers = [];
231        foreach ($last as $item) {
232            $lastUotds[] = $item['DayRecord']['user_id'];
233        }
234        foreach ($ux2 as $item) {
235            $lastUsers[] = $item['User']['id'];
236        }
237        $resultUser = 72;
238        $lastUsersCount = count($lastUsers);
239        for ($i = 0; $i < $lastUsersCount; $i++) {
240            $foundUser = false;
241            $lastUotdsCount = count($lastUotds);
242            for ($j = 0; $j < $lastUotdsCount; $j++) {
243                if ($lastUsers[$i] == $lastUotds[$j]) {
244                    $foundUser = true;
245                }
246            }
247            if (!$foundUser) {
248                $resultUser = $lastUsers[$i];
249
250                break;
251            }
252        }
253        $ux = $this->User->findById($resultUser);
254
255        $recentlyUsed = [];
256        $d = 1;
257        while ($d <= 10) {
258            $ru = $this->DayRecord->find('first', ['conditions' => ['date' => date('Y-m-d', strtotime('-' . $d . ' days'))]]);
259            if ($ru) {
260                array_push($recentlyUsed, $ru);
261            }
262            $d++;
263        }
264        $currentQuote = 'q01';
265        $newQuote = 'q01';
266        $quoteChosen = false;
267        while (!$quoteChosen) {
268            $newQuote = rand(1, 45);
269            if ($newQuote < 10) {
270                $newQuote = 'q0' . $newQuote;
271            } else {
272                $newQuote = 'q' . $newQuote;
273            }
274
275            $f = false;
276            $recentlyUsedCount = count($recentlyUsed);
277            for ($i = 0; $i < $recentlyUsedCount; $i++) {
278                if ($newQuote == $recentlyUsed[$i]['DayRecord']['quote']) {
279                    $f = true;
280                }
281            }
282            if (!$f) {
283                $quoteChosen = true;
284            }
285        }
286        $currentQuote = $newQuote;
287        $dayUserRand = 1;
288        $uotdChosen = false;
289        while (!$uotdChosen) {
290            $dayUserRand = rand(1, 39);
291            $f = false;
292            $recentlyUsedCount = count($recentlyUsed);
293            for ($i = 0; $i < $recentlyUsedCount; $i++) {
294                if ($dayUserRand == $recentlyUsed[$i]['DayRecord']['userbg']) {
295                    $f = true;
296                }
297            }
298            if (!$f) {
299                $uotdChosen = true;
300            }
301        }
302        $activity = $this->TsumegoAttempt->find('all', ['limit' => 40000, 'conditions' => ['DATE(TsumegoAttempt.created)' => date('Y-m-d', strtotime('yesterday'))]]);
303        if (!$activity) {
304            $activity = [];
305        }
306        $visitedProblems = count($activity);
307
308        //how many users today
309        $usersNum = [];
310        $activity = $this->User->find('all', ['limit' => 400, 'order' => 'created DESC']);
311        if (!$activity) {
312            $activity = [];
313        }
314        $activityCount = count($activity);
315        for ($i = 0; $i < $activityCount; $i++) {
316            $a = new DateTime($activity[$i]['User']['created']);
317            if ($a->format('Y-m-d') == $today) {
318                array_push($usersNum, $activity[$i]['User']);
319            }
320        }
321        $gemRand1 = rand(0, 2);
322        $gemRand2 = rand(0, 2);
323        $gemRand3 = rand(0, 2);
324
325        $arch1 = ClassRegistry::init('Achievement')->findById(111);
326        if ($gemRand1 == 0) {
327            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on an easy ddk problem.';
328        } elseif ($gemRand1 == 1) {
329            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a regular ddk problem.';
330        } elseif ($gemRand1 == 2) {
331            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult ddk problem.';
332        }
333        ClassRegistry::init('Achievement')->save($arch1);
334        $arch2 = ClassRegistry::init('Achievement')->findById(112);
335        if ($gemRand2 == 0) {
336            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on an easy sdk problem.';
337        } elseif ($gemRand2 == 1) {
338            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a regular sdk problem.';
339        } elseif ($gemRand2 == 2) {
340            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult sdk problem.';
341        }
342        ClassRegistry::init('Achievement')->save($arch2);
343        $arch3 = ClassRegistry::init('Achievement')->findById(113);
344        if ($gemRand3 == 0) {
345            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on an easy dan problem.';
346        } elseif ($gemRand3 == 1) {
347            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a regular dan problem.';
348        } elseif ($gemRand3 == 2) {
349            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult dan problem.';
350        }
351        ClassRegistry::init('Achievement')->save($arch3);
352
353        $this->DayRecord->create();
354        $dateUser = [];
355        $dateUser['DayRecord']['user_id'] = $ux['User']['id'];
356        $dateUser['DayRecord']['date'] = $today;
357        $dateUser['DayRecord']['solved'] = $ux['User']['reuse3'];
358        $dateUser['DayRecord']['quote'] = $currentQuote;
359        $dateUser['DayRecord']['userbg'] = $dayUserRand;
360        $dateUser['DayRecord']['tsumego'] = $this->getTsumegoOfTheDay();
361        $dateUser['DayRecord']['newTsumego'] = $this->getNewTsumego();
362        $dateUser['DayRecord']['usercount'] = count($usersNum);
363        $dateUser['DayRecord']['visitedproblems'] = $visitedProblems;
364        $dateUser['DayRecord']['gems'] = $gemRand1 . '-' . $gemRand2 . '-' . $gemRand3;
365        $dateUser['DayRecord']['gemCounter1'] = 0;
366        $dateUser['DayRecord']['gemCounter2'] = 0;
367        $dateUser['DayRecord']['gemCounter3'] = 0;
368        $this->DayRecord->save($dateUser);
369
370        ClassRegistry::init('AchievementCondition')->create();
371        $achievementCondition = [];
372        $achievementCondition['AchievementCondition']['user_id'] = $ux['User']['id'];
373        $achievementCondition['AchievementCondition']['set_id'] = 0;
374        $achievementCondition['AchievementCondition']['category'] = 'uotd';
375        $achievementCondition['AchievementCondition']['value'] = 1;
376        ClassRegistry::init('AchievementCondition')->save($achievementCondition);
377
378        //delete duplicated DayRecords
379        $dr = $this->DayRecord->find('all');
380        if (!$dr) {
381            $dr = [];
382        }
383        $duplicates = [];
384        $drCount = count($dr);
385        for ($i = 0; $i < $drCount; $i++) {
386            $alreadyFound = [];
387            for ($j = 0; $j < $drCount; $j++) {
388                if ($i != $j && $dr[$j]['DayRecord']['date'] == $dr[$i]['DayRecord']['date']) {
389                    $found = false;
390                    $alreadyFoundCount = count($alreadyFound);
391                    for ($k = 0; $k < $alreadyFoundCount; $k++) {
392                        if ($alreadyFound[$k]['DayRecord']['id'] == $dr[$i]['DayRecord']['id'] || $alreadyFound[$k]['DayRecord']['id'] == $dr[$j]['DayRecord']['id']) {
393                            $found = true;
394                        }
395                    }
396                    if (!$found) {
397                        array_push($duplicates, $dr[$i]['DayRecord']['date']);
398                        array_push($alreadyFound, $dr[$i]);
399                    }
400                }
401            }
402        }
403        $duplicates = array_count_values($duplicates);
404        foreach ($duplicates as $key => $value) {
405            while ($duplicates[$key] > 1) {
406                $drd = $this->DayRecord->find('first', ['conditions' => ['date' => $key]]);
407                if ($drd) {
408                    $this->DayRecord->delete($drd['DayRecord']['id']);
409                }
410                $duplicates[$key]--;
411            }
412        }
413    }
414
415    public static function deleteUnusedStatuses(int $uid): void {
416        $s = ClassRegistry::init('Set')->find('all', [
417            'conditions' => [
418                'OR' => [
419                    ['public' => 1],
420                    ['public' => 0],
421                ],
422            ],
423        ]) ?: [];
424        $ids = [];
425        $sCount = count($s);
426        for ($i = 0; $i < $sCount; $i++) {
427            $tSet = TsumegoUtil::collectTsumegosFromSet($s[$i]['Set']['id']);
428            foreach ($tSet as $item) {
429                $ids[] = $item['Tsumego']['id'];
430            }
431        }
432        $ut = ClassRegistry::init('TsumegoStatus')->find('all', [
433            'conditions' => [
434                'user_id' => $uid,
435                'NOT' => [
436                    'tsumego_id' => $ids,
437                ],
438            ],
439        ]);
440        if (!$ut) {
441            $ut = [];
442        }
443        $utCount = count($ut);
444        for ($i = 0; $i < $utCount; $i++) {
445            $test1 = ClassRegistry::init('Tsumego')->findById($ut[$i]['TsumegoStatus']['tsumego_id']);
446            $test2 = ClassRegistry::init('SetConnection')->find('first', ['conditions' => ['tsumego_id' => $test1['Tsumego']['id']]]);
447            if (!$test2) {
448                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
449
450                continue;
451            }
452            $test3 = ClassRegistry::init('Set')->find('first', [
453                'id' => $test2['SetConnection']['set_id'],
454                'OR' => [
455                    ['public' => 1],
456                    ['public' => 0],
457                ],
458            ]);
459            if ($test3 == null) {
460                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
461            }
462        }
463    }
464
465    protected function saveSolvedNumber($uid) {
466        $this->loadModel('User');
467        $this->loadModel('TsumegoStatus');
468        $this->loadModel('Set');
469        $this->loadModel('SetConnection');
470
471        $solvedUts2 = 0;
472        $tsumegos = $this->SetConnection->find('all');
473        if (!$tsumegos) {
474            $tsumegos = [];
475        }
476        $uts = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['user_id' => $uid]]);
477        if (!$uts) {
478            $uts = [];
479        }
480        $setKeys = [];
481        $setArray = $this->Set->find('all', ['conditions' => ['public' => 1]]);
482        if (!$setArray) {
483            $setArray = [];
484        }
485
486        $setArrayCount = count($setArray);
487        for ($i = 0; $i < $setArrayCount; $i++) {
488            $setKeys[$setArray[$i]['Set']['id']] = $setArray[$i]['Set']['id'];
489        }
490
491        $scs = [];
492        $tsumegosCount = count($tsumegos);
493        for ($j = 0; $j < $tsumegosCount; $j++) {
494            if (!isset($scs[$tsumegos[$j]['SetConnection']['tsumego_id']])) {
495                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']] = 1;
496            } else {
497                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']]++;
498            }
499        }
500        $utsCount = count($uts);
501        for ($j = 0; $j < $utsCount; $j++) {
502            if ($uts[$j]['TsumegoStatus']['status'] == 'S' || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C') {
503                if (isset($scs[$uts[$j]['TsumegoStatus']['tsumego_id']])) {
504                    $solvedUts2 += $scs[$uts[$j]['TsumegoStatus']['tsumego_id']];
505                }
506            }
507        }
508        Auth::getUser()['solved'] = $solvedUts2;
509        Auth::saveUser();
510
511        return $solvedUts2;
512    }
513
514    public static function convertEloToXp($elo) {
515        $xp = round(pow($elo / 100, 1.55) - 6);
516        if ($xp < 10) {
517            $xp = 10;
518        }
519
520        return $xp;
521    }
522
523    /**
524     * @return void
525     */
526    protected function resetUserElos() {
527        $this->loadModel('User');
528
529        $u = $this->User->find('all', [
530            'conditions' => [
531                'id >=' => 15000,
532                'id <=' => 19000,
533            ],
534        ]);
535        if (!$u) {
536            $u = [];
537        }
538
539        $uCount = count($u);
540        for ($i = 0; $i < $uCount; $i++) {
541            $u[$i]['User']['rating'] = 900;
542            $u[$i]['User']['solved2'] = 0;
543            $this->User->save($u[$i]);
544        }
545    }
546
547    public static function getNewElo($diff, $eloBigger, $activityValue, $tid, $outcome) {
548        $return = [];
549        $t = ClassRegistry::init('Tsumego')->findById($tid);
550        if ($t['Tsumego']['activity_value'] > 300) {
551            $t['Tsumego']['activity_value'] = 300;
552        }
553        $tsumegoAvtivityValue = max(round((2 / 3) * $t['Tsumego']['activity_value']), 15);
554        $kFactor1 = 1;
555        $kFactor2 = 1;
556        if (Auth::isLoggedIn()) {
557            $rating = Auth::getUser()['rating'];
558            if ($rating >= 1500) {
559                $kFactor1 = 1.5;
560                $kFactor2 = 0.9;
561            } elseif ($rating >= 1800) {
562                $kFactor1 = 2;
563                $kFactor2 = 0.8;
564            } elseif ($rating >= 2100) {
565                $kFactor1 = 2.5;
566                $kFactor2 = 0.7;
567            } elseif ($rating >= 2400) {
568                $kFactor1 = 3;
569                $kFactor2 = 0.6;
570            }
571        }
572        if ($diff == 0) {
573            $diff = .1;
574        }
575        $tWin = 0;
576        $tLoss = 0;
577        $uWin = 0;
578        $uLoss = 0;
579        if ($eloBigger == 'u') {
580            $tWin = $diff / $tsumegoAvtivityValue;
581            $tLoss = 0;
582
583            $uWin = log($diff, 2) - $diff / 70;
584            if ($diff <= 100) {
585                $uWin = 5;
586            }
587            $uWin *= $kFactor2;
588            if ($uWin < 1) {
589                $uWin = 1 - $diff / 1400;
590            }
591            if ($uWin > 5) {
592                $uWin = 5;
593            }
594
595            $uLoss = log($diff, 2) * 2.2 - 12;
596            $uLoss *= $kFactor2;
597            if ($uLoss < 5) {
598                $uLoss = 5;
599            }
600            $uLoss *= -1;
601
602            if ($diff > 1000) {
603                $uWin = 0;
604                $uLoss = 0;
605            }
606        } elseif ($eloBigger == 't') {
607            $tWin = 0;
608            $tLoss = $diff / $tsumegoAvtivityValue * (-1);
609
610            $uWin = log($diff, 2) * 2.2 - 11;
611            $uWin *= $kFactor2;
612            if ($uWin < 5) {
613                $uWin = 5;
614            }
615
616            $uLoss = log($diff, 2) - $diff / 70 - 1;
617            if ($diff < 100) {
618                $uLoss = 4;
619            }
620            $uLoss *= $kFactor2;
621            if ($uLoss < 1) {
622                $uLoss = 1 - $diff / 1400;
623            }
624            $uLoss *= -1;
625        }
626
627        $activityValueBase = 1;
628        if ($activityValue < 30) {
629            $activityValueAdd = 0;
630        } elseif ($activityValue < 50) {
631            $activityValueAdd = 0.6;
632        } elseif ($activityValue < 70) {
633            $activityValueAdd = 1.2;
634        } else {
635            $activityValueAdd = 1.8;
636        }
637
638        $activityValueSum = $activityValueBase + ($activityValueAdd / $kFactor1);
639
640        if ($outcome == 'w') {
641            $return['user'] = round($uWin * $activityValueSum, 2);
642            $return['user2'] = $uWin * $activityValueSum;
643            $return['tsumego'] = round($tLoss);
644            $return['tsumego2'] = $tLoss;
645        } else {
646            $return['user'] = round($uLoss * $activityValueSum, 2);
647            $return['user2'] = $uLoss * $activityValueSum;
648            $return['tsumego'] = round($tWin);
649            $return['tsumego2'] = $tWin;
650        }
651
652        return $return;
653    }
654
655    /**
656     * @param int $uid User ID
657     * @param string $action Action type
658     *
659     * @return void
660     */
661    public static function handleContribution($uid, $action) {
662        $uc = ClassRegistry::init('UserContribution')->find('first', ['conditions' => ['user_id' => $uid]]);
663        if ($uc == null) {
664            $uc = [];
665            $uc['UserContribution']['user_id'] = $uid;
666            $uc['UserContribution']['added_tag'] = 0;
667            $uc['UserContribution']['created_tag'] = 0;
668            $uc['UserContribution']['made_proposal'] = 0;
669            $uc['UserContribution']['reviewed'] = 0;
670            $uc['UserContribution']['score'] = 0;
671            ClassRegistry::init('UserContribution')->create();
672        }
673        $uc['UserContribution'][$action] += 1;
674        $uc['UserContribution']['score']
675        = $uc['UserContribution']['added_tag']
676        + $uc['UserContribution']['created_tag'] * 3
677        + $uc['UserContribution']['made_proposal'] * 5
678        + $uc['UserContribution']['reviewed'] * 2;
679        ClassRegistry::init('UserContribution')->save($uc);
680    }
681
682    public static function getAllTags($not) {
683        $a = [];
684        $notApproved = ClassRegistry::init('TagName')->find('all', ['conditions' => ['approved' => 0]]);
685        if (!$notApproved) {
686            $notApproved = [];
687        }
688        $notCount = count($not);
689        for ($i = 0; $i < $notCount; $i++) {
690            array_push($a, $not[$i]['Tag']['tag_name_id']);
691        }
692        $notApprovedCount = count($notApproved);
693        for ($i = 0; $i < $notApprovedCount; $i++) {
694            array_push($a, $notApproved[$i]['TagName']['id']);
695        }
696        $tn = ClassRegistry::init('TagName')->find('all', [
697            'conditions' => [
698                'NOT' => ['id' => $a],
699            ],
700        ]);
701        if (!$tn) {
702            $tn = [];
703        }
704        $sorted = [];
705        $keys = [];
706        $tnCount = count($tn);
707        for ($i = 0; $i < $tnCount; $i++) {
708            array_push($sorted, $tn[$i]['TagName']['name']);
709            $keys[$tn[$i]['TagName']['name']] = $tn[$i];
710        }
711        sort($sorted);
712        $s2 = [];
713        $sortedCount = count($sorted);
714        for ($i = 0; $i < $sortedCount; $i++) {
715            array_push($s2, $keys[$sorted[$i]]);
716        }
717
718        return $s2;
719    }
720
721    /**
722     * @return void
723     */
724    protected function deleteUserBoards() {
725        $this->loadModel('UserBoard');
726        $this->UserBoard->deleteAll(['1 = 1']);
727    }
728
729    /**
730     * @return void
731     */
732    protected function halfXP() {
733        $this->loadModel('TsumegoStatus');
734        $this->loadModel('DayRecord');
735        $week = $this->TsumegoStatus->find('all', ['order' => 'created DESC', 'conditions' => ['status' => 'S']]);
736        if (!$week) {
737            $week = [];
738        }
739        $oneWeek = date('Y-m-d H:i:s', strtotime('-7 days'));
740        $weekCount = count($week);
741        for ($i = 0; $i < $weekCount; $i++) {
742            if ($week[$i]['TsumegoStatus']['created'] < $oneWeek) {
743                if ($week[$i]['TsumegoStatus']['status'] == 'S') {
744                    $week[$i]['TsumegoStatus']['status'] = 'W';
745                    //$this->TsumegoStatus->save($week[$i]);
746                }
747            }
748        }
749    }
750
751    protected function getNewTsumego() {
752        $this->loadModel('Schedule');
753        $date = date('Y-m-d', strtotime('today'));
754        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
755        if (!$s) {
756            $s = [];
757        }
758        $id = 0;
759        $sCount = count($s);
760        for ($i = 0; $i < $sCount; $i++) {
761            $id = $this->publishSingle($s[$i]['Schedule']['tsumego_id'], $s[$i]['Schedule']['set_id'], $s[$i]['Schedule']['date']);
762            $s[$i]['Schedule']['tsumego_id'] = $id;
763            $s[$i]['Schedule']['published'] = 1;
764            $this->Schedule->save($s[$i]);
765        }
766
767        return $id;
768    }
769
770    protected function publishSingle($t = null, $to = null, $date = null) {
771        $this->loadModel('Tsumego');
772        $this->loadModel('Sgf');
773        $this->loadModel('SetConnection');
774        $this->loadModel('PublishDate');
775        $ts = $this->Tsumego->findById($t);
776
777        $id = $this->Tsumego->find('first', ['limit' => 1, 'order' => 'id DESC']);
778        if (!$id) {
779            return null;
780        }
781        $id = $id['Tsumego']['id'];
782        $id += 1;
783
784        $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $ts['Tsumego']['id']]]);
785        if ($scT != null) {
786            $scT['SetConnection']['set_id'] = $to;
787            $scT['SetConnection']['tsumego_id'] = $id;
788            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
789            $this->SetConnection->save($scT);
790        } else {
791            $scT = [];
792            $scT['SetConnection']['set_id'] = $to;
793            $scT['SetConnection']['tsumego_id'] = $id;
794            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
795            $this->SetConnection->create();
796            $this->SetConnection->save($scT);
797        }
798
799        $sid = $ts['Tsumego']['id'];
800        $ts['Tsumego']['id'] = $id;
801        $ts['Tsumego']['created'] = $date . ' 22:00:00';
802        $ts['Tsumego']['solved'] = 0;
803        $ts['Tsumego']['failed'] = 0;
804        $ts['Tsumego']['userWin'] = 0;
805        $ts['Tsumego']['userLoss'] = 0;
806        $this->Tsumego->create();
807        $this->Tsumego->save($ts);
808        $this->Tsumego->delete($sid);
809
810        $sgfs = $this->Sgf->find('all', ['conditions' => ['tsumego_id' => $t]]);
811        if (!$sgfs) {
812            $sgfs = [];
813        }
814        $sgfsCount = count($sgfs);
815        for ($i = 0; $i < $sgfsCount; $i++) {
816            $sgfs[$i]['Sgf']['tsumego_id'] = $id;
817            $this->Sgf->save($sgfs[$i]);
818        }
819        $x = [];
820        $x['PublishDate']['date'] = $date . ' 22:00:00';
821        $x['PublishDate']['tsumego_id'] = $id;
822        $this->PublishDate->create();
823        $this->PublishDate->save($x);
824
825        return $id;
826    }
827
828    protected function getTsumegoOfTheDay() {
829        $this->loadModel('TsumegoAttempt');
830        $this->loadModel('TsumegoRatingAttempt');
831        $this->loadModel('Schedule');
832        $this->loadModel('Tsumego');
833        $this->loadModel('SetConnection');
834
835        $ut = $this->TsumegoRatingAttempt->find('all', ['limit' => 10000, 'order' => 'created DESC', 'conditions' => ['status' => 'S']]);
836        if (!$ut) {
837            $ut = [];
838        }
839        $out = $this->TsumegoAttempt->find('all', ['limit' => 30000, 'order' => 'created DESC', 'conditions' => ['gain >=' => 40]]);
840        if (!$out) {
841            $out = [];
842        }
843
844        $date = date('Y-m-d', strtotime('yesterday'));
845        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
846        if (!$s) {
847            $s = [];
848        }
849        $ids = [];
850        $utCount = count($ut);
851        for ($i = 0; $i < $utCount; $i++) {
852            $date2 = new DateTime($ut[$i]['TsumegoRatingAttempt']['created']);
853            $date2 = $date2->format('Y-m-d');
854            if ($date === $date2) {
855                array_push($ids, $ut[$i]['TsumegoRatingAttempt']['tsumego_id']);
856            }
857        }
858        $ids = array_count_values($ids);
859        $highest = 0;
860        $best = [];
861        foreach ($ids as $key => $value) {
862            if ($value > $highest) {
863                $highest = $value;
864            }
865        }
866        foreach ($ids as $key => $value) {
867            if ($value == $highest) {
868                $x = [];
869                $x[$key] = $value;
870                array_push($best, $x);
871            }
872        }
873        $ids2 = [];
874        $out2 = [];
875        $outCount = count($out);
876        for ($i = 0; $i < $outCount; $i++) {
877            $date2 = new DateTime($out[$i]['TsumegoAttempt']['created']);
878            $date2 = $date2->format('Y-m-d');
879            if ($date === $date2) {
880                array_push($ids2, $out[$i]['TsumegoAttempt']['tsumego_id']);
881                array_push($out2, $out[$i]);
882            }
883        }
884        $ids2 = array_count_values($ids2);
885        $highest = 0;
886        $best2 = [];
887        foreach ($ids2 as $key => $value) {
888            if ($value > $highest) {
889                $highest = $value;
890            }
891        }
892        $done = false;
893        $found = 0;
894        $decrement = 0;
895        $best3 = [];
896        $findNum = 20;
897        while (!$done) {
898            foreach ($ids2 as $key => $value) {
899                if ($value == $highest - $decrement) {
900                    array_push($best2, $key);
901                    array_push($best3, $value);
902                    $found++;
903                }
904            }
905            $decrement++;
906            if ($found < $findNum) {
907                $done = false;
908            } else {
909                $done = true;
910            }
911        }
912        $newBest = [];
913        for ($j = 0; $j < $findNum; $j++) {
914            $newBest[$j] = [];
915        }
916        $out2Count = count($out2);
917        for ($i = 0; $i < $out2Count; $i++) {
918            for ($j = 0; $j < $findNum; $j++) {
919                if ($out2[$i]['TsumegoAttempt']['tsumego_id'] == $best2[$j]) {
920                    $x = [];
921                    $x['tid'] = $out2[$i]['TsumegoAttempt']['tsumego_id'];
922                    $tx = $this->Tsumego->findById($x['tid']);
923                    $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $tx['Tsumego']['id']]]);
924                    $tx['Tsumego']['set_id'] = $scT['SetConnection']['set_id'];
925                    $x['sid'] = $tx['Tsumego']['set_id'];
926                    $x['status'] = $out2[$i]['TsumegoAttempt']['solved'];
927                    $x['seconds'] = $out2[$i]['TsumegoAttempt']['seconds'];
928
929                    $newBest[$j][] = $x;
930                }
931            }
932        }
933        $newBestCount = count($newBest);
934        for ($i = 0; $i < $newBestCount; $i++) {
935            $sum = 0;
936            $newBestICount = count($newBest[$i]);
937            for ($j = 0; $j < $newBestICount; $j++) {
938                if ($newBest[$i][$j]['seconds'] != null) {
939                    if ($newBest[$i][$j]['seconds'] > 300) {
940                        $newBest[$i][$j]['seconds'] = 300;
941                    }
942                    $sum += $newBest[$i][$j]['seconds'];
943                }
944            }
945            $sum = $sum * count($newBest[$i]);
946            $newBest[$i]['sum'] = $sum;
947        }
948        $highest = 0;
949        $hid = 0;
950        $newBestCount = count($newBest);
951        for ($i = 0; $i < $newBestCount; $i++) {
952            if ($newBest[$i]['sum'] > $highest && $newBest[$i][0]['sid'] != 104 && $newBest[$i][0]['sid'] != 105 && $newBest[$i][0]['sid'] != 117) {
953                $yesterday = false;
954                $sCount = count($s);
955                for ($j = 0; $j < $sCount; $j++) {
956                    if ($newBest[$i][0]['tid'] == $s[$j]['Schedule']['tsumego_id']) {
957                        $yesterday = true;
958                    }
959                }
960                if (!$yesterday) {
961                    $highest = $newBest[$i]['sum'];
962                    $hid = $i;
963                }
964            }
965        }
966
967        return $newBest[$hid][0]['tid'];
968    }
969
970    protected function ratingMatch($elo) {
971        if ($elo >= 3000) {
972            $td = 10;//10d
973        } elseif ($elo >= 2900) {
974            $td = 10;//9d
975        } elseif ($elo >= 2800) {
976            $td = 10;//8d
977        } elseif ($elo >= 2700) {
978            $td = 10;//7d x2700
979        } elseif ($elo >= 2600) {
980            $td = 9;//6d x2600
981        } elseif ($elo >= 2500) {
982            $td = 8;//5d x2500
983        } elseif ($elo >= 2400) {
984            $td = 7;//4d
985        } elseif ($elo >= 2300) {
986            $td = 7;//3d x2350
987        } elseif ($elo >= 2200) {
988            $td = 6;//2d
989        } elseif ($elo >= 2100) {
990            $td = 6;//1d x2150
991        } elseif ($elo >= 2000) {
992            $td = 5;//1k
993        } elseif ($elo >= 1900) {
994            $td = 5;//2k x1950
995        } elseif ($elo >= 1800) {
996            $td = 4;//3k
997        } elseif ($elo >= 1700) {
998            $td = 4;//4k x1750
999        } elseif ($elo >= 1600) {
1000            $td = 3;//5k
1001        } elseif ($elo >= 1500) {
1002            $td = 3;//6k x1500
1003        } elseif ($elo >= 1400) {
1004            $td = 3;//7k
1005        } elseif ($elo >= 1300) {
1006            $td = 2;//8k
1007        } elseif ($elo >= 1200) {
1008            $td = 2;//9k x1200
1009        } elseif ($elo >= 1100) {
1010            $td = 2;//10k
1011        } elseif ($elo >= 1000) {
1012            $td = 1;//11k
1013        } elseif ($elo >= 900) {
1014            $td = 1;//12k x900
1015        } elseif ($elo >= 800) {
1016            $td = 1;//13k
1017        } elseif ($elo >= 700) {
1018            $td = 1;//14k
1019        } elseif ($elo >= 600) {
1020            $td = 1;//15k
1021        } elseif ($elo >= 500) {
1022            $td = 1;//16k
1023        } elseif ($elo >= 400) {
1024            $td = 1;//17k
1025        } elseif ($elo >= 300) {
1026            $td = 1;//18k
1027        } elseif ($elo >= 200) {
1028            $td = 1;//19k
1029        } elseif ($elo >= 100) {
1030            $td = 1;//20k
1031        } else {
1032            $td = 1;
1033        }
1034
1035        return $td;
1036    }
1037
1038    protected function rating2($d) {
1039        if ($d == 10) {
1040            $elo = 2700;
1041        } elseif ($d == 9) {
1042            $elo = 2600;
1043        } elseif ($d == 8) {
1044            $elo = 2500;
1045        } elseif ($d == 7) {
1046            $elo = 2350;
1047        } elseif ($d == 6) {
1048            $elo = 2150;
1049        } elseif ($d == 5) {
1050            $elo = 1950;
1051        } elseif ($d == 4) {
1052            $elo = 1750;
1053        } elseif ($d == 3) {
1054            $elo = 1500;
1055        } elseif ($d == 2) {
1056            $elo = 1200;
1057        } elseif ($d == 1) {
1058            $elo = 900;
1059        } else {
1060            $elo = 1500;
1061        }
1062
1063        return $elo;
1064    }
1065
1066    public static function encrypt($str = null) {
1067        $secret_key = 'my_simple_secret_keyx';
1068        $secret_iv = 'my_simple_secret_ivx';
1069        $encrypt_method = 'AES-256-CBC';
1070        $key = hash('sha256', $secret_key);
1071        $iv = substr(hash('sha256', $secret_iv), 0, 16);
1072
1073        return base64_encode(openssl_encrypt($str, $encrypt_method, $key, 0, $iv));
1074    }
1075
1076    public static function decrypt($str = null) {
1077        $string = $str;
1078        $secret_key = 'my_simple_secret_keyx';
1079        $secret_iv = 'my_simple_secret_ivx';
1080        $encrypt_method = 'AES-256-CBC';
1081        $key = hash('sha256', $secret_key);
1082        $iv = substr(hash('sha256', $secret_iv), 0, 16);
1083
1084        return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
1085    }
1086
1087    protected function checkPictureLarge($u) {
1088        if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
1089            return '<img class="google-profile-image-large" src="/img/google/' . $u['User']['picture'] . '">' . substr($u['User']['name'], 3);
1090        }
1091
1092        return $u['User']['name'];
1093    }
1094    public static function checkPicture($user) {
1095        if (substr($user['name'], 0, 3) == 'g__' && $user['external_id'] != null) {
1096            return '<img class="google-profile-image" src="/img/google/' . $user['picture'] . '">' . substr($user['name'], 3);
1097        }
1098
1099        return $user['name'];
1100    }
1101
1102    public static function getTsumegoRankx($t) {
1103        if ($t <= 0) {
1104            return '15k';
1105        }
1106        if ($t > 0 && $t <= 22) {
1107            $tRank = '5d';
1108        } elseif ($t <= 26.5) {
1109            $tRank = '4d';
1110        } elseif ($t <= 30) {
1111            $tRank = '3d';
1112        } elseif ($t <= 34) {
1113            $tRank = '2d';
1114        } elseif ($t <= 38) {
1115            $tRank = '1d';
1116        } elseif ($t <= 42) {
1117            $tRank = '1k';
1118        } elseif ($t <= 46) {
1119            $tRank = '2k';
1120        } elseif ($t <= 50) {
1121            $tRank = '3k';
1122        } elseif ($t <= 54.5) {
1123            $tRank = '4k';
1124        } elseif ($t <= 58.5) {
1125            $tRank = '5k';
1126        } elseif ($t <= 63) {
1127            $tRank = '6k';
1128        } elseif ($t <= 67) {
1129            $tRank = '7k';
1130        } elseif ($t <= 70.8) {
1131            $tRank = '8k';
1132        } elseif ($t <= 74.8) {
1133            $tRank = '9k';
1134        } elseif ($t <= 79) {
1135            $tRank = '10k';
1136        } elseif ($t <= 83.5) {
1137            $tRank = '11k';
1138        } elseif ($t <= 88) {
1139            $tRank = '12k';
1140        } elseif ($t <= 92) {
1141            $tRank = '13k';
1142        } elseif ($t <= 96) {
1143            $tRank = '14k';
1144        } else {
1145            $tRank = '15k';
1146        }
1147
1148        return $tRank;
1149    }
1150    protected function adjustElo($v) {
1151        $add = 0;
1152        if ($v >= 1700) {
1153            $add = 110;
1154        } elseif ($v >= 1600) {
1155            $add = 110;
1156        } elseif ($v >= 1700) {
1157            $add = 100;
1158        } elseif ($v >= 1600) {
1159            $add = 90;
1160        } elseif ($v >= 1500) {
1161            $add = 80;
1162        } elseif ($v >= 1400) {
1163            $add = 70;
1164        } elseif ($v >= 1300) {
1165            $add = 60;
1166        } elseif ($v >= 1200) {
1167            $add = 60;
1168        } elseif ($v >= 1100) {
1169            $add = 50;
1170        } elseif ($v >= 1000) {
1171            $add = 50;
1172        } else {
1173            $add = 0;
1174        }
1175
1176        return $v + $add;
1177    }
1178
1179    public static function getTsumegoElo($rank, $p = null) {
1180        if ($p != null) {
1181            $p *= 100;
1182        } else {
1183            $p = 0;
1184        }
1185        $elo = 600;
1186        if ($rank == '9d') {
1187            $elo = round(2900 + $p);
1188        } elseif ($rank == '8d') {
1189            $elo = round(2800 + $p);
1190        } elseif ($rank == '7d') {
1191            $elo = round(2700 + $p);
1192        } elseif ($rank == '6d') {
1193            $elo = round(2600 + $p);
1194        } elseif ($rank == '5d') {
1195            $elo = round(2500 + $p);
1196        } elseif ($rank == '4d') {
1197            $elo = round(2400 + $p);
1198        } elseif ($rank == '3d') {
1199            $elo = round(2300 + $p);
1200        } elseif ($rank == '2d') {
1201            $elo = round(2200 + $p);
1202        } elseif ($rank == '1d') {
1203            $elo = round(2100 + $p);
1204        } elseif ($rank == '1k') {
1205            $elo = round(2000 + $p);
1206        } elseif ($rank == '2k') {
1207            $elo = round(1900 + $p);
1208        } elseif ($rank == '3k') {
1209            $elo = round(1800 + $p);
1210        } elseif ($rank == '4k') {
1211            $elo = round(1700 + $p);
1212        } elseif ($rank == '5k') {
1213            $elo = round(1600 + $p);
1214        } elseif ($rank == '6k') {
1215            $elo = round(1500 + $p);
1216        } elseif ($rank == '7k') {
1217            $elo = round(1400 + $p);
1218        } elseif ($rank == '8k') {
1219            $elo = round(1300 + $p);
1220        } elseif ($rank == '9k') {
1221            $elo = round(1200 + $p);
1222        } elseif ($rank == '10k') {
1223            $elo = round(1100 + $p);
1224        } elseif ($rank == '11k') {
1225            $elo = round(1000 + $p);
1226        } elseif ($rank == '12k') {
1227            $elo = round(900 + $p);
1228        } elseif ($rank == '13k') {
1229            $elo = round(800 + $p);
1230        } elseif ($rank == '14k') {
1231            $elo = round(700 + $p);
1232        } elseif ($rank == '15k' || $rank == '16k' || $rank == '17k' || $rank == '18k' || $rank == '19k' || $rank == '20k' || $rank == '21k') {
1233            $elo = round(600 + $p);
1234        }
1235
1236        return $elo;
1237    }
1238    protected function getTsumegoRankVal($t) {
1239        if ($t <= 0) {
1240            return 0;
1241        }
1242        if ($t > 0 && $t <= 22) {
1243            return 22 - $t;
1244        }
1245        if ($t <= 26.5) {
1246            return 26.5 - $t;
1247        }
1248        if ($t <= 30) {
1249            return 30 - $t;
1250        }
1251        if ($t <= 34) {
1252            return 34 - $t;
1253        }
1254        if ($t <= 38) {
1255            return 38 - $t;
1256        }
1257        if ($t <= 42) {
1258            return 42 - $t;
1259        }
1260        if ($t <= 46) {
1261            return 46 - $t;
1262        }
1263        if ($t <= 50) {
1264            return 50 - $t;
1265        }
1266        if ($t <= 54.5) {
1267            return 54.5 - $t;
1268        }
1269        if ($t <= 58.5) {
1270            return 58.5 - $t;
1271        }
1272        if ($t <= 63) {
1273            return 63 - $t;
1274        }
1275        if ($t <= 67) {
1276            return 67 - $t;
1277        }
1278        if ($t <= 70.8) {
1279            return 70.8 - $t;
1280        }
1281        if ($t <= 74.8) {
1282            return 74.8 - $t;
1283        }
1284        if ($t <= 79) {
1285            return 79 - $t;
1286        }
1287        if ($t <= 83.5) {
1288            return 83.5 - $t;
1289        }
1290        if ($t <= 88) {
1291            return 88 - $t;
1292        }
1293        if ($t <= 92) {
1294            return 92 - $t;
1295        }
1296        if ($t <= 96) {
1297            return 96 - $t;
1298        }
1299
1300        return 100 - $t;
1301    }
1302    protected function getTsumegoRankMax($t) {
1303        if ($t <= 0) {
1304            return 100 - 96;
1305        }
1306        if ($t > 0 && $t <= 22) {
1307            return 22;
1308        }
1309        if ($t <= 26.5) {
1310            return 26.5 - 22;
1311        }
1312        if ($t <= 30) {
1313            return 30 - 26.5;
1314        }
1315        if ($t <= 34) {
1316            return 34 - 30;
1317        }
1318        if ($t <= 38) {
1319            return 38 - 34;
1320        }
1321        if ($t <= 42) {
1322            return 42 - 38;
1323        }
1324        if ($t <= 46) {
1325            return 46 - 42;
1326        }
1327        if ($t <= 50) {
1328            return 50 - 46;
1329        }
1330        if ($t <= 54.5) {
1331            return 54.5 - 50;
1332        }
1333        if ($t <= 58.5) {
1334            return 58.5 - 54.5;
1335        }
1336        if ($t <= 63) {
1337            return 63 - 58.5;
1338        }
1339        if ($t <= 67) {
1340            return 67 - 63;
1341        }
1342        if ($t <= 70.8) {
1343            return 70.8 - 67;
1344        }
1345        if ($t <= 74.8) {
1346            return 74.8 - 70.8;
1347        }
1348        if ($t <= 79) {
1349            return 79 - 74.8;
1350        }
1351        if ($t <= 83.5) {
1352            return 83.5 - 79;
1353        }
1354        if ($t <= 88) {
1355            return 88 - 83.5;
1356        }
1357        if ($t <= 92) {
1358            return 92 - 88;
1359        }
1360        if ($t <= 96) {
1361            return 96 - 92;
1362        }
1363
1364        return 100 - 96;
1365    }
1366
1367    public static function saveDanSolveCondition($solvedTsumegoRank, $tId): void {
1368        if ($solvedTsumegoRank == '1d' || $solvedTsumegoRank == '2d' || $solvedTsumegoRank == '3d' || $solvedTsumegoRank == '4d' || $solvedTsumegoRank == '5d') {
1369            $danSolveCategory = 'danSolve' . $solvedTsumegoRank;
1370            $danSolveCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1371                'order' => 'value DESC',
1372                'conditions' => [
1373                    'user_id' => Auth::getUserID(),
1374                    'category' => $danSolveCategory,
1375                ],
1376            ]);
1377            if (!$danSolveCondition) {
1378                $danSolveCondition = [];
1379                $danSolveCondition['AchievementCondition']['value'] = 0;
1380                ClassRegistry::init('AchievementCondition')->create();
1381            }
1382            $danSolveCondition['AchievementCondition']['category'] = $danSolveCategory;
1383            $danSolveCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1384            $danSolveCondition['AchievementCondition']['set_id'] = $tId;
1385            $danSolveCondition['AchievementCondition']['value']++;
1386
1387            ClassRegistry::init('AchievementCondition')->save($danSolveCondition);
1388        }
1389    }
1390
1391    public static function updateSprintCondition(bool $trigger = false): void {
1392        if (Auth::isLoggedIn()) {
1393            $sprintCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1394                'order' => 'value DESC',
1395                'conditions' => [
1396                    'user_id' => Auth::getUserID(),
1397                    'category' => 'sprint',
1398                ],
1399            ]);
1400            if (!$sprintCondition) {
1401                $sprintCondition = [];
1402                $sprintCondition['AchievementCondition']['value'] = 0;
1403                ClassRegistry::init('AchievementCondition')->create();
1404            }
1405            $sprintCondition['AchievementCondition']['category'] = 'sprint';
1406            $sprintCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1407            if ($trigger) {
1408                $sprintCondition['AchievementCondition']['value']++;
1409            } else {
1410                $sprintCondition['AchievementCondition']['value'] = 0;
1411            }
1412            ClassRegistry::init('AchievementCondition')->save($sprintCondition);
1413        }
1414    }
1415
1416    public static function updateGoldenCondition(bool $trigger = false): void {
1417        $goldenCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1418            'order' => 'value DESC',
1419            'conditions' => [
1420                'user_id' => Auth::getUserID(),
1421                'category' => 'golden',
1422            ],
1423        ]);
1424        if (!$goldenCondition) {
1425            $goldenCondition = [];
1426            $goldenCondition['AchievementCondition']['value'] = 0;
1427            ClassRegistry::init('AchievementCondition')->create();
1428        }
1429        $goldenCondition['AchievementCondition']['category'] = 'golden';
1430        $goldenCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1431        if ($trigger) {
1432            $goldenCondition['AchievementCondition']['value']++;
1433        } else {
1434            $goldenCondition['AchievementCondition']['value'] = 0;
1435        }
1436        ClassRegistry::init('AchievementCondition')->save($goldenCondition);
1437    }
1438
1439    public static function setPotionCondition(): void {
1440        $potionCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1441            'order' => 'value DESC',
1442            'conditions' => [
1443                'user_id' => Auth::getUserID(),
1444                'category' => 'potion',
1445            ],
1446        ]);
1447        if (!$potionCondition) {
1448            $potionCondition = [];
1449            ClassRegistry::init('AchievementCondition')->create();
1450        }
1451        $potionCondition['AchievementCondition']['category'] = 'potion';
1452        $potionCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1453        $potionCondition['AchievementCondition']['value'] = 1;
1454        ClassRegistry::init('AchievementCondition')->save($potionCondition);
1455    }
1456
1457    public static function updateGems(string $rank): void {
1458        $datex = new DateTime('today');
1459        $dateGem = ClassRegistry::init('DayRecord')->find('first', ['conditions' => ['date' => $datex->format('Y-m-d')]]);
1460        if ($dateGem != null) {
1461            $gems = explode('-', $dateGem['DayRecord']['gems']);
1462            $gemValue = '';
1463            $gemValue2 = '';
1464            $gemValue3 = '';
1465            $condition1 = 500;
1466            $condition2 = 200;
1467            $condition3 = 5;
1468            $found1 = false;
1469            $found2 = false;
1470            $found3 = false;
1471            if ($rank == '15k' || $rank == '14k' || $rank == '13k' || $rank == '12k' || $rank == '11k' || $rank == '10k') {
1472                if ($gems[0] == 0) {
1473                    $gemValue = '15k';
1474                } elseif ($gems[0] == 1) {
1475                    $gemValue = '12k';
1476                } elseif ($gems[0] == 2) {
1477                    $gemValue = '10k';
1478                }
1479                if ($rank == $gemValue) {
1480                    $dateGem['DayRecord']['gemCounter1']++;
1481                    if ($dateGem['DayRecord']['gemCounter1'] == $condition1) {
1482                        $found1 = true;
1483                    }
1484                }
1485            } elseif ($rank == '9k' || $rank == '8k' || $rank == '7k' || $rank == '6k' || $rank == '5k' || $rank == '4k' || $rank == '3k' || $rank == '2k' || $rank == '1k') {
1486                if ($gems[1] == 0) {
1487                    $gemValue = '9k';
1488                    $gemValue2 = 'x';
1489                    $gemValue3 = 'y';
1490                } elseif ($gems[1] == 1) {
1491                    $gemValue = '6k';
1492                    $gemValue2 = '5k';
1493                    $gemValue3 = '4k';
1494                } elseif ($gems[1] == 2) {
1495                    $gemValue = 'x';
1496                    $gemValue2 = '2k';
1497                    $gemValue3 = '1k';
1498                }
1499                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1500                    $dateGem['DayRecord']['gemCounter2']++;
1501                    if ($dateGem['DayRecord']['gemCounter2'] == $condition2) {
1502                        $found2 = true;
1503                    }
1504                }
1505            } elseif ($rank == '1d' || $rank == '2d' || $rank == '3d' || $rank == '4d' || $rank == '5d' || $rank == '6d' || $rank == '7d') {
1506                if ($gems[2] == 0) {
1507                    $gemValue = '1d';
1508                    $gemValue2 = '2d';
1509                    $gemValue3 = '3d';
1510                } elseif ($gems[2] == 1) {
1511                    $gemValue = '2d';
1512                    $gemValue2 = '3d';
1513                    $gemValue3 = '4d';
1514                } elseif ($gems[2] == 2) {
1515                    $gemValue = '5d';
1516                    $gemValue2 = '6d';
1517                    $gemValue3 = '7d';
1518                }
1519                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1520                    $dateGem['DayRecord']['gemCounter3']++;
1521                    if ($dateGem['DayRecord']['gemCounter3'] == $condition3) {
1522                        $found3 = true;
1523                    }
1524                }
1525            }
1526            if ($found1) {
1527                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1528                    'order' => 'value DESC',
1529                    'conditions' => [
1530                        'user_id' => Auth::getUserID(),
1531                        'category' => 'emerald',
1532                    ],
1533                ]);
1534                if ($aCondition == null) {
1535                    $aCondition = [];
1536                    $aCondition['AchievementCondition']['category'] = 'emerald';
1537                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1538                    $aCondition['AchievementCondition']['value'] = 1;
1539                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1540                } else {
1541                    $dateGem['DayRecord']['gemCounter1']--;
1542                }
1543            } elseif ($found2) {
1544                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1545                    'order' => 'value DESC',
1546                    'conditions' => [
1547                        'user_id' => Auth::getUserID(),
1548                        'category' => 'sapphire',
1549                    ],
1550                ]);
1551                if ($aCondition == null) {
1552                    $aCondition = [];
1553                    $aCondition['AchievementCondition']['category'] = 'sapphire';
1554                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1555                    $aCondition['AchievementCondition']['value'] = 1;
1556                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1557                } else {
1558                    $dateGem['DayRecord']['gemCounter2']--;
1559                }
1560            } elseif ($found3) {
1561                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1562                    'order' => 'value DESC',
1563                    'conditions' => [
1564                        'user_id' => Auth::getUserID(),
1565                        'category' => 'ruby',
1566                    ],
1567                ]);
1568                if ($aCondition == null) {
1569                    $aCondition = [];
1570                    $aCondition['AchievementCondition']['category'] = 'ruby';
1571                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1572                    $aCondition['AchievementCondition']['value'] = 1;
1573                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1574                } else {
1575                    $dateGem['DayRecord']['gemCounter3']--;
1576                }
1577            }
1578        }
1579        ClassRegistry::init('DayRecord')->save($dateGem);
1580    }
1581
1582    public static function checkProblemNumberAchievements() {
1583        if (!Auth::isLoggedIn()) {
1584            return;
1585        }
1586
1587        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1588        if (!$buffer) {
1589            $buffer = [];
1590        }
1591        $existingAs = [];
1592        $bufferCount = count($buffer);
1593        for ($i = 0; $i < $bufferCount; $i++) {
1594            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1595        }
1596        $as = [];
1597        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1598        $updated = [];
1599
1600        $achievementId = 1;
1601        $solvedCount = Auth::getUser()['solved'];
1602        if ($solvedCount >= 1000 && !isset($existingAs[$achievementId])) {
1603            $as['AchievementStatus']['achievement_id'] = $achievementId;
1604            ClassRegistry::init('AchievementStatus')->create();
1605            ClassRegistry::init('AchievementStatus')->save($as);
1606            array_push($updated, $achievementId);
1607        }
1608        $achievementId = 2;
1609        if ($solvedCount >= 2000 && !isset($existingAs[$achievementId])) {
1610            $as['AchievementStatus']['achievement_id'] = $achievementId;
1611            ClassRegistry::init('AchievementStatus')->create();
1612            ClassRegistry::init('AchievementStatus')->save($as);
1613            array_push($updated, $achievementId);
1614        }
1615        $achievementId = 3;
1616        if ($solvedCount >= 3000 && !isset($existingAs[$achievementId])) {
1617            $as['AchievementStatus']['achievement_id'] = $achievementId;
1618            ClassRegistry::init('AchievementStatus')->create();
1619            ClassRegistry::init('AchievementStatus')->save($as);
1620            array_push($updated, $achievementId);
1621        }
1622        $achievementId = 4;
1623        if ($solvedCount >= 4000 && !isset($existingAs[$achievementId])) {
1624            $as['AchievementStatus']['achievement_id'] = $achievementId;
1625            ClassRegistry::init('AchievementStatus')->create();
1626            ClassRegistry::init('AchievementStatus')->save($as);
1627            array_push($updated, $achievementId);
1628        }
1629        $achievementId = 5;
1630        if ($solvedCount >= 5000 && !isset($existingAs[$achievementId])) {
1631            $as['AchievementStatus']['achievement_id'] = $achievementId;
1632            ClassRegistry::init('AchievementStatus')->create();
1633            ClassRegistry::init('AchievementStatus')->save($as);
1634            array_push($updated, $achievementId);
1635        }
1636        $achievementId = 6;
1637        if ($solvedCount >= 6000 && !isset($existingAs[$achievementId])) {
1638            $as['AchievementStatus']['achievement_id'] = $achievementId;
1639            ClassRegistry::init('AchievementStatus')->create();
1640            ClassRegistry::init('AchievementStatus')->save($as);
1641            array_push($updated, $achievementId);
1642        }
1643        $achievementId = 7;
1644        if ($solvedCount >= 7000 && !isset($existingAs[$achievementId])) {
1645            $as['AchievementStatus']['achievement_id'] = $achievementId;
1646            ClassRegistry::init('AchievementStatus')->create();
1647            ClassRegistry::init('AchievementStatus')->save($as);
1648            array_push($updated, $achievementId);
1649        }
1650        $achievementId = 8;
1651        if ($solvedCount >= 8000 && !isset($existingAs[$achievementId])) {
1652            $as['AchievementStatus']['achievement_id'] = $achievementId;
1653            ClassRegistry::init('AchievementStatus')->create();
1654            ClassRegistry::init('AchievementStatus')->save($as);
1655            array_push($updated, $achievementId);
1656        }
1657        $achievementId = 9;
1658        if ($solvedCount >= 9000 && !isset($existingAs[$achievementId])) {
1659            $as['AchievementStatus']['achievement_id'] = $achievementId;
1660            ClassRegistry::init('AchievementStatus')->create();
1661            ClassRegistry::init('AchievementStatus')->save($as);
1662            array_push($updated, $achievementId);
1663        }
1664        $achievementId = 10;
1665        if ($solvedCount >= 10000 && !isset($existingAs[$achievementId])) {
1666            $as['AchievementStatus']['achievement_id'] = $achievementId;
1667            ClassRegistry::init('AchievementStatus')->create();
1668            ClassRegistry::init('AchievementStatus')->save($as);
1669            array_push($updated, $achievementId);
1670        }
1671        //uotd achievement
1672        $achievementId = 11;
1673        if (!isset($existingAs[$achievementId])) {
1674            $condition = ClassRegistry::init('AchievementCondition')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => 'uotd']]);
1675            if ($condition != null) {
1676                $as['AchievementStatus']['achievement_id'] = $achievementId;
1677                ClassRegistry::init('AchievementStatus')->create();
1678                ClassRegistry::init('AchievementStatus')->save($as);
1679                array_push($updated, $achievementId);
1680            }
1681        }
1682
1683        $updatedCount = count($updated);
1684        for ($i = 0; $i < $updatedCount; $i++) {
1685            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1686            $updated[$i] = [];
1687            $updated[$i][0] = $a['Achievement']['name'];
1688            $updated[$i][1] = $a['Achievement']['description'];
1689            $updated[$i][2] = $a['Achievement']['image'];
1690            $updated[$i][3] = $a['Achievement']['color'];
1691            $updated[$i][4] = $a['Achievement']['xp'];
1692            $updated[$i][5] = $a['Achievement']['id'];
1693        }
1694
1695        return $updated;
1696    }
1697
1698    public static function checkDanSolveAchievements() {
1699        if (Auth::isLoggedIn()) {
1700            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1701            if (!$buffer) {
1702                $buffer = [];
1703            }
1704            $ac = ClassRegistry::init('AchievementCondition')->find('all', [
1705                'order' => 'category ASC',
1706                'conditions' => [
1707                    'user_id' => Auth::getUserID(),
1708                    'OR' => [
1709                        ['category' => 'danSolve1d'],
1710                        ['category' => 'danSolve2d'],
1711                        ['category' => 'danSolve3d'],
1712                        ['category' => 'danSolve4d'],
1713                        ['category' => 'danSolve5d'],
1714                        ['category' => 'emerald'],
1715                        ['category' => 'sapphire'],
1716                        ['category' => 'ruby'],
1717                        ['category' => 'sprint'],
1718                        ['category' => 'golden'],
1719                        ['category' => 'potion'],
1720                    ],
1721                ],
1722            ]);
1723            if (!$ac) {
1724                $ac = [];
1725            }
1726            $ac1 = [];
1727            $acCount = count($ac);
1728            for ($i = 0; $i < $acCount; $i++) {
1729                if ($ac[$i]['AchievementCondition']['category'] == 'danSolve1d') {
1730                    $ac1['1d'] = $ac[$i]['AchievementCondition']['value'];
1731                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve2d') {
1732                    $ac1['2d'] = $ac[$i]['AchievementCondition']['value'];
1733                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve3d') {
1734                    $ac1['3d'] = $ac[$i]['AchievementCondition']['value'];
1735                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve4d') {
1736                    $ac1['4d'] = $ac[$i]['AchievementCondition']['value'];
1737                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve5d') {
1738                    $ac1['5d'] = $ac[$i]['AchievementCondition']['value'];
1739                } elseif ($ac[$i]['AchievementCondition']['category'] == 'emerald') {
1740                    $ac1['emerald'] = $ac[$i]['AchievementCondition']['value'];
1741                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sapphire') {
1742                    $ac1['sapphire'] = $ac[$i]['AchievementCondition']['value'];
1743                } elseif ($ac[$i]['AchievementCondition']['category'] == 'ruby') {
1744                    $ac1['ruby'] = $ac[$i]['AchievementCondition']['value'];
1745                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sprint') {
1746                    $ac1['sprint'] = $ac[$i]['AchievementCondition']['value'];
1747                } elseif ($ac[$i]['AchievementCondition']['category'] == 'golden') {
1748                    $ac1['golden'] = $ac[$i]['AchievementCondition']['value'];
1749                } elseif ($ac[$i]['AchievementCondition']['category'] == 'potion') {
1750                    $ac1['potion'] = $ac[$i]['AchievementCondition']['value'];
1751                }
1752            }
1753
1754            $existingAs = [];
1755            $bufferCount = count($buffer);
1756            for ($i = 0; $i < $bufferCount; $i++) {
1757                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1758            }
1759            $as = [];
1760            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1761            $updated = [];
1762            $achievementId = 101;
1763            if ($ac1['1d'] > 0 && !isset($existingAs[$achievementId])) {
1764                $as['AchievementStatus']['achievement_id'] = $achievementId;
1765                ClassRegistry::init('AchievementStatus')->create();
1766                ClassRegistry::init('AchievementStatus')->save($as);
1767                array_push($updated, $achievementId);
1768            }
1769            $achievementId = 102;
1770            if ($ac1['2d'] > 0 && !isset($existingAs[$achievementId])) {
1771                $as['AchievementStatus']['achievement_id'] = $achievementId;
1772                ClassRegistry::init('AchievementStatus')->create();
1773                ClassRegistry::init('AchievementStatus')->save($as);
1774                array_push($updated, $achievementId);
1775            }
1776            $achievementId = 103;
1777            if ($ac1['3d'] > 0 && !isset($existingAs[$achievementId])) {
1778                $as['AchievementStatus']['achievement_id'] = $achievementId;
1779                ClassRegistry::init('AchievementStatus')->create();
1780                ClassRegistry::init('AchievementStatus')->save($as);
1781                array_push($updated, $achievementId);
1782            }
1783            $achievementId = 104;
1784            if ($ac1['4d'] > 0 && !isset($existingAs[$achievementId])) {
1785                $as['AchievementStatus']['achievement_id'] = $achievementId;
1786                ClassRegistry::init('AchievementStatus')->create();
1787                ClassRegistry::init('AchievementStatus')->save($as);
1788                array_push($updated, $achievementId);
1789            }
1790            $achievementId = 105;
1791            if ($ac1['5d'] > 0 && !isset($existingAs[$achievementId])) {
1792                $as['AchievementStatus']['achievement_id'] = $achievementId;
1793                ClassRegistry::init('AchievementStatus')->create();
1794                ClassRegistry::init('AchievementStatus')->save($as);
1795                array_push($updated, $achievementId);
1796            }
1797            $achievementId = 106;
1798            if ($ac1['1d'] >= 10 && !isset($existingAs[$achievementId])) {
1799                $as['AchievementStatus']['achievement_id'] = $achievementId;
1800                ClassRegistry::init('AchievementStatus')->create();
1801                ClassRegistry::init('AchievementStatus')->save($as);
1802                array_push($updated, $achievementId);
1803            }
1804            $achievementId = 107;
1805            if ($ac1['2d'] >= 10 && !isset($existingAs[$achievementId])) {
1806                $as['AchievementStatus']['achievement_id'] = $achievementId;
1807                ClassRegistry::init('AchievementStatus')->create();
1808                ClassRegistry::init('AchievementStatus')->save($as);
1809                array_push($updated, $achievementId);
1810            }
1811            $achievementId = 108;
1812            if ($ac1['3d'] >= 10 && !isset($existingAs[$achievementId])) {
1813                $as['AchievementStatus']['achievement_id'] = $achievementId;
1814                ClassRegistry::init('AchievementStatus')->create();
1815                ClassRegistry::init('AchievementStatus')->save($as);
1816                array_push($updated, $achievementId);
1817            }
1818            $achievementId = 109;
1819            if ($ac1['4d'] >= 10 && !isset($existingAs[$achievementId])) {
1820                $as['AchievementStatus']['achievement_id'] = $achievementId;
1821                ClassRegistry::init('AchievementStatus')->create();
1822                ClassRegistry::init('AchievementStatus')->save($as);
1823                array_push($updated, $achievementId);
1824            }
1825            $achievementId = 110;
1826            if ($ac1['5d'] >= 10 && !isset($existingAs[$achievementId])) {
1827                $as['AchievementStatus']['achievement_id'] = $achievementId;
1828                ClassRegistry::init('AchievementStatus')->create();
1829                ClassRegistry::init('AchievementStatus')->save($as);
1830                array_push($updated, $achievementId);
1831            }
1832            $achievementId = 111;
1833            if (isset($ac1['emerald'])) {
1834                if ($ac1['emerald'] == 1 && !isset($existingAs[$achievementId])) {
1835                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1836                    ClassRegistry::init('AchievementStatus')->create();
1837                    ClassRegistry::init('AchievementStatus')->save($as);
1838                    array_push($updated, $achievementId);
1839                }
1840            }
1841            $achievementId = 112;
1842            if (isset($ac1['sapphire'])) {
1843                if ($ac1['sapphire'] == 1 && !isset($existingAs[$achievementId])) {
1844                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1845                    ClassRegistry::init('AchievementStatus')->create();
1846                    ClassRegistry::init('AchievementStatus')->save($as);
1847                    array_push($updated, $achievementId);
1848                }
1849            }
1850            $achievementId = 113;
1851            if (isset($ac1['ruby'])) {
1852                if ($ac1['ruby'] == 1 && !isset($existingAs[$achievementId])) {
1853                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1854                    ClassRegistry::init('AchievementStatus')->create();
1855                    ClassRegistry::init('AchievementStatus')->save($as);
1856                    array_push($updated, $achievementId);
1857                }
1858            }
1859            $achievementId = 114;
1860            if (!isset($existingAs[$achievementId]) && isset($existingAs[111]) && isset($existingAs[112]) && isset($existingAs[113])) {
1861                $as['AchievementStatus']['achievement_id'] = $achievementId;
1862                ClassRegistry::init('AchievementStatus')->create();
1863                ClassRegistry::init('AchievementStatus')->save($as);
1864                array_push($updated, $achievementId);
1865            }
1866            $achievementId = 96;
1867            if (!isset($existingAs[$achievementId]) && $ac1['sprint'] >= 30) {
1868                $as['AchievementStatus']['achievement_id'] = $achievementId;
1869                ClassRegistry::init('AchievementStatus')->create();
1870                ClassRegistry::init('AchievementStatus')->save($as);
1871                array_push($updated, $achievementId);
1872            }
1873            $achievementId = 97;
1874            if (!isset($existingAs[$achievementId]) && $ac1['golden'] >= 10) {
1875                $as['AchievementStatus']['achievement_id'] = $achievementId;
1876                ClassRegistry::init('AchievementStatus')->create();
1877                ClassRegistry::init('AchievementStatus')->save($as);
1878                array_push($updated, $achievementId);
1879            }
1880            $achievementId = 98;
1881            if (!isset($existingAs[$achievementId]) && $ac1['potion'] >= 1) {
1882                $as['AchievementStatus']['achievement_id'] = $achievementId;
1883                ClassRegistry::init('AchievementStatus')->create();
1884                ClassRegistry::init('AchievementStatus')->save($as);
1885                array_push($updated, $achievementId);
1886            }
1887            $updatedCount = count($updated);
1888            for ($i = 0; $i < $updatedCount; $i++) {
1889                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1890                $updated[$i] = [];
1891                $updated[$i][0] = $a['Achievement']['name'];
1892                $updated[$i][1] = $a['Achievement']['description'];
1893                $updated[$i][2] = $a['Achievement']['image'];
1894                $updated[$i][3] = $a['Achievement']['color'];
1895                $updated[$i][4] = $a['Achievement']['xp'];
1896                $updated[$i][5] = $a['Achievement']['id'];
1897            }
1898
1899            return $updated;
1900        }
1901    }
1902
1903    protected function checkForLocked($t, $setsWithPremium) {
1904        $scCheck = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $t['Tsumego']['id']]]);
1905        if ($scCheck && in_array($scCheck['SetConnection']['set_id'], $setsWithPremium) && !Auth::hasPremium()) {
1906            $t['Tsumego']['locked'] = true;
1907        } else {
1908            $t['Tsumego']['locked'] = false;
1909        }
1910
1911        return $t;
1912    }
1913    public static function checkNoErrorAchievements() {
1914        if (Auth::isLoggedIn()) {
1915
1916            $ac = ClassRegistry::init('AchievementCondition')->find('first', [
1917                'order' => 'value DESC',
1918                'conditions' => [
1919                    'user_id' => Auth::getUserID(),
1920                    'category' => 'err',
1921                ],
1922            ]);
1923
1924            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1925            if (!$buffer) {
1926                $buffer = [];
1927            }
1928            $existingAs = [];
1929            $bufferCount = count($buffer);
1930            for ($i = 0; $i < $bufferCount; $i++) {
1931                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1932            }
1933            $as = [];
1934            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1935            $updated = [];
1936
1937            $achievementId = 53;
1938            if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
1939                $as['AchievementStatus']['achievement_id'] = $achievementId;
1940                ClassRegistry::init('AchievementStatus')->create();
1941                ClassRegistry::init('AchievementStatus')->save($as);
1942                array_push($updated, $achievementId);
1943            }
1944            $achievementId = 54;
1945            if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
1946                $as['AchievementStatus']['achievement_id'] = $achievementId;
1947                ClassRegistry::init('AchievementStatus')->create();
1948                ClassRegistry::init('AchievementStatus')->save($as);
1949                array_push($updated, $achievementId);
1950            }
1951            $achievementId = 55;
1952            if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
1953                $as['AchievementStatus']['achievement_id'] = $achievementId;
1954                ClassRegistry::init('AchievementStatus')->create();
1955                ClassRegistry::init('AchievementStatus')->save($as);
1956                array_push($updated, $achievementId);
1957            }
1958            $achievementId = 56;
1959            if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
1960                $as['AchievementStatus']['achievement_id'] = $achievementId;
1961                ClassRegistry::init('AchievementStatus')->create();
1962                ClassRegistry::init('AchievementStatus')->save($as);
1963                array_push($updated, $achievementId);
1964            }
1965            $achievementId = 57;
1966            if ($ac['AchievementCondition']['value'] >= 100 && !isset($existingAs[$achievementId])) {
1967                $as['AchievementStatus']['achievement_id'] = $achievementId;
1968                ClassRegistry::init('AchievementStatus')->create();
1969                ClassRegistry::init('AchievementStatus')->save($as);
1970                array_push($updated, $achievementId);
1971            }
1972            $achievementId = 58;
1973            if ($ac['AchievementCondition']['value'] >= 200 && !isset($existingAs[$achievementId])) {
1974                $as['AchievementStatus']['achievement_id'] = $achievementId;
1975                ClassRegistry::init('AchievementStatus')->create();
1976                ClassRegistry::init('AchievementStatus')->save($as);
1977                array_push($updated, $achievementId);
1978            }
1979            $updatedCount = count($updated);
1980            for ($i = 0; $i < $updatedCount; $i++) {
1981                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1982                $updated[$i] = [];
1983                $updated[$i][0] = $a['Achievement']['name'];
1984                $updated[$i][1] = $a['Achievement']['description'];
1985                $updated[$i][2] = $a['Achievement']['image'];
1986                $updated[$i][3] = $a['Achievement']['color'];
1987                $updated[$i][4] = $a['Achievement']['xp'];
1988                $updated[$i][5] = $a['Achievement']['id'];
1989            }
1990
1991            return $updated;
1992        }
1993    }
1994
1995    protected function checkTimeModeAchievements() {
1996        $this->loadModel('Achievement');
1997        $this->loadModel('AchievementStatus');
1998        $this->loadModel('TimeModeSession');
1999
2000        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2001        if (!$buffer) {
2002            $buffer = [];
2003        }
2004        $existingAs = [];
2005        $bufferCount = count($buffer);
2006        for ($i = 0; $i < $bufferCount; $i++) {
2007            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2008        }
2009        $as = [];
2010        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2011        $updated = [];
2012
2013        $rBlitz = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_BLITZ, 'user_id' => Auth::getUserID()]]);
2014        if (!$rBlitz) {
2015            $rBlitz = [];
2016        }
2017        $rFast = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_FAST_SPEED, 'user_id' => Auth::getUserID()]]);
2018        if (!$rFast) {
2019            $rFast = [];
2020        }
2021        $rSlow = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_SLOW_SPEED, 'user_id' => Auth::getUserID()]]);
2022        if (!$rSlow) {
2023            $rSlow = [];
2024        }
2025        $r = $this->TimeModeSession->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2026        if (!$r) {
2027            $r = [];
2028        }
2029
2030        $timeModeAchievements = [];
2031        for ($i = 70; $i <= 91; $i++) {
2032            $timeModeAchievements[$i] = false;
2033        }
2034        $rCount = count($r);
2035        for ($i = 0; $i < $rCount; $i++) {
2036            if ($r[$i]['TimeModeSession']['status'] == 's') {
2037                if ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k') {
2038                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2039                        $timeModeAchievements[70] = true;
2040                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2041                        $timeModeAchievements[76] = true;
2042                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2043                        $timeModeAchievements[82] = true;
2044                    }
2045                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k') {
2046                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2047                        $timeModeAchievements[71] = true;
2048                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2049                        $timeModeAchievements[77] = true;
2050                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2051                        $timeModeAchievements[83] = true;
2052                    }
2053                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k') {
2054                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2055                        $timeModeAchievements[72] = true;
2056                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2057                        $timeModeAchievements[78] = true;
2058                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2059                        $timeModeAchievements[84] = true;
2060                    }
2061                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k') {
2062                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2063                        $timeModeAchievements[73] = true;
2064                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2065                        $timeModeAchievements[79] = true;
2066                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2067                        $timeModeAchievements[85] = true;
2068                    }
2069                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k') {
2070                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2071                        $timeModeAchievements[74] = true;
2072                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2073                        $timeModeAchievements[80] = true;
2074                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2075                        $timeModeAchievements[86] = true;
2076                    }
2077                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d') {
2078                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
2079                        $timeModeAchievements[75] = true;
2080                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
2081                        $timeModeAchievements[81] = true;
2082                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
2083                        $timeModeAchievements[87] = true;
2084                    }
2085                }
2086            }
2087            if ($r[$i]['TimeModeSession']['points'] >= 850
2088            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2089            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2090            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d')) {
2091                $timeModeAchievements[91] = true;
2092            }
2093            if ($r[$i]['TimeModeSession']['points'] >= 875
2094            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2095            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2096            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k')) {
2097                $timeModeAchievements[90] = true;
2098            }
2099            if ($r[$i]['TimeModeSession']['points'] >= 900
2100            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2101            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2102            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
2103            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k')) {
2104                $timeModeAchievements[89] = true;
2105            }
2106            if ($r[$i]['TimeModeSession']['points'] >= 950
2107            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
2108            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
2109            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
2110            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '9k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '10k')) {
2111                $timeModeAchievements[88] = true;
2112            }
2113        }
2114        for ($i = 70; $i <= 91; $i++) {
2115            $achievementId = $i;
2116            if ($timeModeAchievements[$achievementId] == true && !isset($existingAs[$achievementId])) {
2117                $as['AchievementStatus']['achievement_id'] = $achievementId;
2118                ClassRegistry::init('AchievementStatus')->create();
2119                ClassRegistry::init('AchievementStatus')->save($as);
2120                array_push($updated, $achievementId);
2121            }
2122        }
2123        $updatedCount = count($updated);
2124        for ($i = 0; $i < $updatedCount; $i++) {
2125            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2126            $updated[$i] = [];
2127            $updated[$i][0] = $a['Achievement']['name'];
2128            $updated[$i][1] = $a['Achievement']['description'];
2129            $updated[$i][2] = $a['Achievement']['image'];
2130            $updated[$i][3] = $a['Achievement']['color'];
2131            $updated[$i][4] = $a['Achievement']['xp'];
2132            $updated[$i][5] = $a['Achievement']['id'];
2133        }
2134
2135        return $updated;
2136    }
2137
2138    public static function checkRatingAchievements() {
2139        if (!Auth::isLoggedIn()) {
2140            return;
2141        }
2142
2143        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2144        if (!$buffer) {
2145            $buffer = [];
2146        }
2147        $existingAs = [];
2148        $bufferCount = count($buffer);
2149        for ($i = 0; $i < $bufferCount; $i++) {
2150            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2151        }
2152        $as = [];
2153        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2154        $updated = [];
2155
2156        $achievementId = 59;
2157        $currentElo = Auth::getUser()['rating'];
2158        if ($currentElo >= 1500 && !isset($existingAs[$achievementId])) {
2159            $as['AchievementStatus']['achievement_id'] = $achievementId;
2160            ClassRegistry::init('AchievementStatus')->create();
2161            ClassRegistry::init('AchievementStatus')->save($as);
2162            array_push($updated, $achievementId);
2163        }
2164        $achievementId = 60;
2165        if ($currentElo >= 1600 && !isset($existingAs[$achievementId])) {
2166            $as['AchievementStatus']['achievement_id'] = $achievementId;
2167            ClassRegistry::init('AchievementStatus')->create();
2168            ClassRegistry::init('AchievementStatus')->save($as);
2169            array_push($updated, $achievementId);
2170        }
2171        $achievementId = 61;
2172        if ($currentElo >= 1700 && !isset($existingAs[$achievementId])) {
2173            $as['AchievementStatus']['achievement_id'] = $achievementId;
2174            ClassRegistry::init('AchievementStatus')->create();
2175            ClassRegistry::init('AchievementStatus')->save($as);
2176            array_push($updated, $achievementId);
2177        }
2178        $achievementId = 62;
2179        if ($currentElo >= 1800 && !isset($existingAs[$achievementId])) {
2180            $as['AchievementStatus']['achievement_id'] = $achievementId;
2181            ClassRegistry::init('AchievementStatus')->create();
2182            ClassRegistry::init('AchievementStatus')->save($as);
2183            array_push($updated, $achievementId);
2184        }
2185        $achievementId = 63;
2186        if ($currentElo >= 1900 && !isset($existingAs[$achievementId])) {
2187            $as['AchievementStatus']['achievement_id'] = $achievementId;
2188            ClassRegistry::init('AchievementStatus')->create();
2189            ClassRegistry::init('AchievementStatus')->save($as);
2190            array_push($updated, $achievementId);
2191        }
2192        $achievementId = 64;
2193        if ($currentElo >= 2000 && !isset($existingAs[$achievementId])) {
2194            $as['AchievementStatus']['achievement_id'] = $achievementId;
2195            ClassRegistry::init('AchievementStatus')->create();
2196            ClassRegistry::init('AchievementStatus')->save($as);
2197            array_push($updated, $achievementId);
2198        }
2199        $achievementId = 65;
2200        if ($currentElo >= 2100 && !isset($existingAs[$achievementId])) {
2201            $as['AchievementStatus']['achievement_id'] = $achievementId;
2202            ClassRegistry::init('AchievementStatus')->create();
2203            ClassRegistry::init('AchievementStatus')->save($as);
2204            array_push($updated, $achievementId);
2205        }
2206        $achievementId = 66;
2207        if ($currentElo >= 2200 && !isset($existingAs[$achievementId])) {
2208            $as['AchievementStatus']['achievement_id'] = $achievementId;
2209            ClassRegistry::init('AchievementStatus')->create();
2210            ClassRegistry::init('AchievementStatus')->save($as);
2211            array_push($updated, $achievementId);
2212        }
2213        $achievementId = 67;
2214        if ($currentElo >= 2300 && !isset($existingAs[$achievementId])) {
2215            $as['AchievementStatus']['achievement_id'] = $achievementId;
2216            ClassRegistry::init('AchievementStatus')->create();
2217            ClassRegistry::init('AchievementStatus')->save($as);
2218            array_push($updated, $achievementId);
2219        }
2220        $achievementId = 68;
2221        if ($currentElo >= 2400 && !isset($existingAs[$achievementId])) {
2222            $as['AchievementStatus']['achievement_id'] = $achievementId;
2223            ClassRegistry::init('AchievementStatus')->create();
2224            ClassRegistry::init('AchievementStatus')->save($as);
2225            array_push($updated, $achievementId);
2226        }
2227        $achievementId = 69;
2228        if ($currentElo >= 2500 && !isset($existingAs[$achievementId])) {
2229            $as['AchievementStatus']['achievement_id'] = $achievementId;
2230            ClassRegistry::init('AchievementStatus')->create();
2231            ClassRegistry::init('AchievementStatus')->save($as);
2232            array_push($updated, $achievementId);
2233        }
2234        $updatedCount = count($updated);
2235        for ($i = 0; $i < $updatedCount; $i++) {
2236            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2237            $updated[$i] = [];
2238            $updated[$i][0] = $a['Achievement']['name'];
2239            $updated[$i][1] = $a['Achievement']['description'];
2240            $updated[$i][2] = $a['Achievement']['image'];
2241            $updated[$i][3] = $a['Achievement']['color'];
2242            $updated[$i][4] = $a['Achievement']['xp'];
2243            $updated[$i][5] = $a['Achievement']['id'];
2244        }
2245
2246        return $updated;
2247    }
2248
2249    public static function checkLevelAchievements() {
2250        if (!Auth::isLoggedIn()) {
2251            return;
2252        }
2253        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2254        if (!$buffer) {
2255            $buffer = [];
2256        }
2257        $existingAs = [];
2258        $bufferCount = count($buffer);
2259        for ($i = 0; $i < $bufferCount; $i++) {
2260            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2261        }
2262        $as = [];
2263        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2264        $updated = [];
2265
2266        $achievementId = 36;
2267        $userLevel = Auth::getUser()['level'];
2268        if ($userLevel >= 10 && !isset($existingAs[$achievementId])) {
2269            $as['AchievementStatus']['achievement_id'] = $achievementId;
2270            ClassRegistry::init('AchievementStatus')->create();
2271            ClassRegistry::init('AchievementStatus')->save($as);
2272            array_push($updated, $achievementId);
2273        }
2274        $achievementId = 37;
2275        if ($userLevel >= 20 && !isset($existingAs[$achievementId])) {
2276            $as['AchievementStatus']['achievement_id'] = $achievementId;
2277            ClassRegistry::init('AchievementStatus')->create();
2278            ClassRegistry::init('AchievementStatus')->save($as);
2279            array_push($updated, $achievementId);
2280        }
2281        $achievementId = 38;
2282        if ($userLevel >= 30 && !isset($existingAs[$achievementId])) {
2283            $as['AchievementStatus']['achievement_id'] = $achievementId;
2284            ClassRegistry::init('AchievementStatus')->create();
2285            ClassRegistry::init('AchievementStatus')->save($as);
2286            array_push($updated, $achievementId);
2287        }
2288        $achievementId = 39;
2289        if ($userLevel >= 40 && !isset($existingAs[$achievementId])) {
2290            $as['AchievementStatus']['achievement_id'] = $achievementId;
2291            ClassRegistry::init('AchievementStatus')->create();
2292            ClassRegistry::init('AchievementStatus')->save($as);
2293            array_push($updated, $achievementId);
2294        }
2295        $achievementId = 40;
2296        if ($userLevel >= 50 && !isset($existingAs[$achievementId])) {
2297            $as['AchievementStatus']['achievement_id'] = $achievementId;
2298            ClassRegistry::init('AchievementStatus')->create();
2299            ClassRegistry::init('AchievementStatus')->save($as);
2300            array_push($updated, $achievementId);
2301        }
2302        $achievementId = 41;
2303        if ($userLevel >= 60 && !isset($existingAs[$achievementId])) {
2304            $as['AchievementStatus']['achievement_id'] = $achievementId;
2305            ClassRegistry::init('AchievementStatus')->create();
2306            ClassRegistry::init('AchievementStatus')->save($as);
2307            array_push($updated, $achievementId);
2308        }
2309        $achievementId = 42;
2310        if ($userLevel >= 70 && !isset($existingAs[$achievementId])) {
2311            $as['AchievementStatus']['achievement_id'] = $achievementId;
2312            ClassRegistry::init('AchievementStatus')->create();
2313            ClassRegistry::init('AchievementStatus')->save($as);
2314            array_push($updated, $achievementId);
2315        }
2316        $achievementId = 43;
2317        if ($userLevel >= 80 && !isset($existingAs[$achievementId])) {
2318            $as['AchievementStatus']['achievement_id'] = $achievementId;
2319            ClassRegistry::init('AchievementStatus')->create();
2320            ClassRegistry::init('AchievementStatus')->save($as);
2321            array_push($updated, $achievementId);
2322        }
2323        $achievementId = 44;
2324        if ($userLevel >= 90 && !isset($existingAs[$achievementId])) {
2325            $as['AchievementStatus']['achievement_id'] = $achievementId;
2326            ClassRegistry::init('AchievementStatus')->create();
2327            ClassRegistry::init('AchievementStatus')->save($as);
2328            array_push($updated, $achievementId);
2329        }
2330        $achievementId = 45;
2331        if ($userLevel >= 100 && !isset($existingAs[$achievementId])) {
2332            $as['AchievementStatus']['achievement_id'] = $achievementId;
2333            ClassRegistry::init('AchievementStatus')->create();
2334            ClassRegistry::init('AchievementStatus')->save($as);
2335            array_push($updated, $achievementId);
2336        }
2337        $achievementId = 100;
2338        if (Auth::hasPremium() && !isset($existingAs[$achievementId])) {
2339            $as['AchievementStatus']['achievement_id'] = $achievementId;
2340            ClassRegistry::init('AchievementStatus')->create();
2341            ClassRegistry::init('AchievementStatus')->save($as);
2342            array_push($updated, $achievementId);
2343        }
2344        $updatedCount = count($updated);
2345        for ($i = 0; $i < $updatedCount; $i++) {
2346            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2347            $updated[$i] = [];
2348            $updated[$i][0] = $a['Achievement']['name'];
2349            $updated[$i][1] = $a['Achievement']['description'];
2350            $updated[$i][2] = $a['Achievement']['image'];
2351            $updated[$i][3] = $a['Achievement']['color'];
2352            $updated[$i][4] = $a['Achievement']['xp'];
2353            $updated[$i][5] = $a['Achievement']['id'];
2354        }
2355
2356        return $updated;
2357    }
2358
2359    protected function checkSetCompletedAchievements() {
2360        $this->loadModel('Set');
2361        $this->loadModel('Tsumego');
2362        $this->loadModel('Achievement');
2363        $this->loadModel('AchievementStatus');
2364        $this->loadModel('AchievementCondition');
2365
2366        $ac = ClassRegistry::init('AchievementCondition')->find('first', [
2367            'order' => 'value DESC',
2368            'conditions' => [
2369                'user_id' => Auth::getUserID(),
2370                'category' => 'set',
2371            ],
2372        ]);
2373
2374        if (!$ac) {
2375            return [];
2376        }
2377
2378        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2379        if (!$buffer) {
2380            $buffer = [];
2381        }
2382        $existingAs = [];
2383        $bufferCount = count($buffer);
2384        for ($i = 0; $i < $bufferCount; $i++) {
2385            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2386        }
2387        $as = [];
2388        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2389        $updated = [];
2390
2391        $achievementId = 47;
2392        if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
2393            $as['AchievementStatus']['achievement_id'] = $achievementId;
2394            ClassRegistry::init('AchievementStatus')->create();
2395            ClassRegistry::init('AchievementStatus')->save($as);
2396            array_push($updated, $achievementId);
2397        }
2398        $achievementId = 48;
2399        if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
2400            $as['AchievementStatus']['achievement_id'] = $achievementId;
2401            ClassRegistry::init('AchievementStatus')->create();
2402            ClassRegistry::init('AchievementStatus')->save($as);
2403            array_push($updated, $achievementId);
2404        }
2405        $achievementId = 49;
2406        if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
2407            $as['AchievementStatus']['achievement_id'] = $achievementId;
2408            ClassRegistry::init('AchievementStatus')->create();
2409            ClassRegistry::init('AchievementStatus')->save($as);
2410            array_push($updated, $achievementId);
2411        }
2412        $achievementId = 50;
2413        if ($ac['AchievementCondition']['value'] >= 40 && !isset($existingAs[$achievementId])) {
2414            $as['AchievementStatus']['achievement_id'] = $achievementId;
2415            ClassRegistry::init('AchievementStatus')->create();
2416            ClassRegistry::init('AchievementStatus')->save($as);
2417            array_push($updated, $achievementId);
2418        }
2419        $achievementId = 51;
2420        if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
2421            $as['AchievementStatus']['achievement_id'] = $achievementId;
2422            ClassRegistry::init('AchievementStatus')->create();
2423            ClassRegistry::init('AchievementStatus')->save($as);
2424            array_push($updated, $achievementId);
2425        }
2426        $achievementId = 52;
2427        if ($ac['AchievementCondition']['value'] >= 60 && !isset($existingAs[$achievementId])) {
2428            $as['AchievementStatus']['achievement_id'] = $achievementId;
2429            ClassRegistry::init('AchievementStatus')->create();
2430            ClassRegistry::init('AchievementStatus')->save($as);
2431            array_push($updated, $achievementId);
2432        }
2433        $updatedCount = count($updated);
2434        for ($i = 0; $i < $updatedCount; $i++) {
2435            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2436            $updated[$i] = [];
2437            $updated[$i][0] = $a['Achievement']['name'];
2438            $updated[$i][1] = $a['Achievement']['description'];
2439            $updated[$i][2] = $a['Achievement']['image'];
2440            $updated[$i][3] = $a['Achievement']['color'];
2441            $updated[$i][4] = $a['Achievement']['xp'];
2442            $updated[$i][5] = $a['Achievement']['id'];
2443        }
2444
2445        return $updated;
2446    }
2447
2448    protected function setAchievementSpecial($s = null) {
2449        $this->loadModel('Set');
2450        $this->loadModel('Tsumego');
2451        $this->loadModel('TsumegoStatus');
2452        $this->loadModel('Achievement');
2453        $this->loadModel('AchievementStatus');
2454        $this->loadModel('SetConnection');
2455
2456        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2457        if (!$buffer) {
2458            $buffer = [];
2459        }
2460        $existingAs = [];
2461        $bufferCount = count($buffer);
2462        for ($i = 0; $i < $bufferCount; $i++) {
2463            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2464        }
2465        $as = [];
2466        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2467        $updated = [];
2468
2469        $tsIds = [];
2470        $completed = '';
2471        if ($s == 'cc1') {
2472            $ts1 = TsumegoUtil::collectTsumegosFromSet(50);
2473            $ts2 = TsumegoUtil::collectTsumegosFromSet(52);
2474            $ts3 = TsumegoUtil::collectTsumegosFromSet(53);
2475            $ts4 = TsumegoUtil::collectTsumegosFromSet(54);
2476            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2477            $tsCount = count($ts);
2478            for ($i = 0; $i < $tsCount; $i++) {
2479                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2480            }
2481            $uts = $this->TsumegoStatus->find('all', [
2482                'conditions' => [
2483                    'user_id' => Auth::getUserID(),
2484                    'tsumego_id' => $tsIds,
2485                ],
2486            ]);
2487            if (!$uts) {
2488                $uts = [];
2489            }
2490            $counter = 0;
2491            $utsCount = count($uts);
2492            for ($j = 0; $j < $utsCount; $j++) {
2493                for ($k = 0; $k < $tsCount; $k++) {
2494                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2495                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2496                        $counter++;
2497                    }
2498                }
2499            }
2500            if ($counter == count($ts)) {
2501                $completed = $s;
2502            }
2503        } elseif ($s == 'cc2') {
2504            $ts1 = TsumegoUtil::collectTsumegosFromSet(41);
2505            $ts2 = TsumegoUtil::collectTsumegosFromSet(49);
2506            $ts3 = TsumegoUtil::collectTsumegosFromSet(65);
2507            $ts4 = TsumegoUtil::collectTsumegosFromSet(66);
2508            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2509            $tsCount = count($ts);
2510            for ($i = 0; $i < $tsCount; $i++) {
2511                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2512            }
2513            $uts = $this->TsumegoStatus->find('all', [
2514                'conditions' => [
2515                    'user_id' => Auth::getUserID(),
2516                    'tsumego_id' => $tsIds,
2517                ],
2518            ]);
2519            if (!$uts) {
2520                $uts = [];
2521            }
2522            $counter = 0;
2523            $utsCount = count($uts);
2524            for ($j = 0; $j < $utsCount; $j++) {
2525                for ($k = 0; $k < $tsCount; $k++) {
2526                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2527                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2528                        $counter++;
2529                    }
2530                }
2531            }
2532            if ($counter == count($ts)) {
2533                $completed = $s;
2534            }
2535        } elseif ($s == 'cc3') {
2536            $ts1 = TsumegoUtil::collectTsumegosFromSet(186);
2537            $ts2 = TsumegoUtil::collectTsumegosFromSet(187);
2538            $ts3 = TsumegoUtil::collectTsumegosFromSet(196);
2539            $ts4 = TsumegoUtil::collectTsumegosFromSet(203);
2540            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2541            $tsCount = count($ts);
2542            for ($i = 0; $i < $tsCount; $i++) {
2543                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2544            }
2545            $uts = $this->TsumegoStatus->find('all', [
2546                'conditions' => [
2547                    'user_id' => Auth::getUserID(),
2548                    'tsumego_id' => $tsIds,
2549                ],
2550            ]);
2551            if (!$uts) {
2552                $uts = [];
2553            }
2554            $counter = 0;
2555            $utsCount = count($uts);
2556            for ($j = 0; $j < $utsCount; $j++) {
2557                for ($k = 0; $k < $tsCount; $k++) {
2558                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2559                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2560                        $counter++;
2561                    }
2562                }
2563            }
2564            if ($counter == count($ts)) {
2565                $completed = $s;
2566            }
2567        } elseif ($s == '1000w1') {
2568            $ts1 = TsumegoUtil::collectTsumegosFromSet(190);
2569            $ts2 = TsumegoUtil::collectTsumegosFromSet(193);
2570            $ts3 = TsumegoUtil::collectTsumegosFromSet(198);
2571            $ts = array_merge($ts1, $ts2, $ts3);
2572            $tsCount = count($ts);
2573            for ($i = 0; $i < $tsCount; $i++) {
2574                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2575            }
2576            $uts = $this->TsumegoStatus->find('all', [
2577                'conditions' => [
2578                    'user_id' => Auth::getUserID(),
2579                    'tsumego_id' => $tsIds,
2580                ],
2581            ]);
2582            if (!$uts) {
2583                $uts = [];
2584            }
2585            $counter = 0;
2586            $utsCount = count($uts);
2587            for ($j = 0; $j < $utsCount; $j++) {
2588                for ($k = 0; $k < $tsCount; $k++) {
2589                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2590                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2591                        $counter++;
2592                    }
2593                }
2594            }
2595            if ($counter == count($ts)) {
2596                $completed = $s;
2597            }
2598        } elseif ($s == '1000w2') {
2599            $ts = TsumegoUtil::collectTsumegosFromSet(216);
2600            $tsCount = count($ts);
2601            for ($i = 0; $i < $tsCount; $i++) {
2602                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2603            }
2604            $uts = $this->TsumegoStatus->find('all', [
2605                'conditions' => [
2606                    'user_id' => Auth::getUserID(),
2607                    'tsumego_id' => $tsIds,
2608                ],
2609            ]);
2610            if (!$uts) {
2611                $uts = [];
2612            }
2613            $counter = 0;
2614            $utsCount = count($uts);
2615            for ($j = 0; $j < $utsCount; $j++) {
2616                for ($k = 0; $k < $tsCount; $k++) {
2617                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2618                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2619                        $counter++;
2620                    }
2621                }
2622            }
2623            if ($counter == count($ts)) {
2624                $completed = $s;
2625            }
2626        }
2627
2628        $achievementId = 92;
2629        if ($completed == 'cc1' && !isset($existingAs[$achievementId])) {
2630            $as['AchievementStatus']['achievement_id'] = $achievementId;
2631            ClassRegistry::init('AchievementStatus')->create();
2632            ClassRegistry::init('AchievementStatus')->save($as);
2633            array_push($updated, $achievementId);
2634        }
2635        $achievementId = 93;
2636        if ($completed == 'cc2' && !isset($existingAs[$achievementId])) {
2637            $as['AchievementStatus']['achievement_id'] = $achievementId;
2638            ClassRegistry::init('AchievementStatus')->create();
2639            ClassRegistry::init('AchievementStatus')->save($as);
2640            array_push($updated, $achievementId);
2641        }
2642        $achievementId = 94;
2643        if ($completed == 'cc3' && !isset($existingAs[$achievementId])) {
2644            $as['AchievementStatus']['achievement_id'] = $achievementId;
2645            ClassRegistry::init('AchievementStatus')->create();
2646            ClassRegistry::init('AchievementStatus')->save($as);
2647            array_push($updated, $achievementId);
2648        }
2649        $achievementId = 95;
2650        if ($completed == '1000w1' && !isset($existingAs[$achievementId])) {
2651            $as['AchievementStatus']['achievement_id'] = $achievementId;
2652            ClassRegistry::init('AchievementStatus')->create();
2653            ClassRegistry::init('AchievementStatus')->save($as);
2654            array_push($updated, $achievementId);
2655        }
2656        $achievementId = 115;
2657        if ($completed == '1000w2' && !isset($existingAs[$achievementId])) {
2658            $as['AchievementStatus']['achievement_id'] = $achievementId;
2659            ClassRegistry::init('AchievementStatus')->create();
2660            ClassRegistry::init('AchievementStatus')->save($as);
2661            array_push($updated, $achievementId);
2662        }
2663        $updatedCount = count($updated);
2664        for ($i = 0; $i < $updatedCount; $i++) {
2665            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2666            $updated[$i] = [];
2667            $updated[$i][0] = $a['Achievement']['name'];
2668            $updated[$i][1] = $a['Achievement']['description'];
2669            $updated[$i][2] = $a['Achievement']['image'];
2670            $updated[$i][3] = $a['Achievement']['color'];
2671            $updated[$i][4] = $a['Achievement']['xp'];
2672            $updated[$i][5] = $a['Achievement']['id'];
2673        }
2674
2675        return $updated;
2676    }
2677
2678    protected function checkSetAchievements($sid = null) {
2679        $this->loadModel('Set');
2680        $this->loadModel('Tsumego');
2681        $this->loadModel('Achievement');
2682        $this->loadModel('AchievementStatus');
2683        $this->loadModel('AchievementCondition');
2684
2685        //$tNum = count($this->Tsumego->find('all', array('conditions' => array('set_id' => $sid))));
2686        $tNum = count(TsumegoUtil::collectTsumegosFromSet($sid));
2687        $s = $this->Set->findById($sid);
2688        $acA = ClassRegistry::init('AchievementCondition')->find('first', [
2689            'order' => 'value DESC',
2690            'conditions' => [
2691                'set_id' => $sid,
2692                'user_id' => Auth::getUserID(),
2693                'category' => '%',
2694            ],
2695        ]);
2696        if (!$acA) {
2697            return [];
2698        }
2699        $acS = ClassRegistry::init('AchievementCondition')->find('first', [
2700            'order' => 'value ASC',
2701            'conditions' => [
2702                'set_id' => $sid,
2703                'user_id' => Auth::getUserID(),
2704                'category' => 's',
2705            ],
2706        ]);
2707        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2708        if (!$buffer) {
2709            $buffer = [];
2710        }
2711        $existingAs = [];
2712        $bufferCount = count($buffer);
2713        for ($i = 0; $i < $bufferCount; $i++) {
2714            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2715        }
2716        $as = [];
2717        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2718        $updated = [];
2719
2720        $achievementId = 99;
2721        if ($sid == -1 && !isset($existingAs[$achievementId])) {
2722            $as['AchievementStatus']['achievement_id'] = $achievementId;
2723            ClassRegistry::init('AchievementStatus')->create();
2724            ClassRegistry::init('AchievementStatus')->save($as);
2725            array_push($updated, $achievementId);
2726        }
2727        if ($tNum >= 100) {
2728            if ($s['Set']['difficulty'] < 1300) {
2729                $achievementId = 12;
2730                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2731                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2732                    ClassRegistry::init('AchievementStatus')->create();
2733                    ClassRegistry::init('AchievementStatus')->save($as);
2734                    array_push($updated, $achievementId);
2735                }
2736                $achievementId = 13;
2737                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2738                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2739                    ClassRegistry::init('AchievementStatus')->create();
2740                    ClassRegistry::init('AchievementStatus')->save($as);
2741                    array_push($updated, $achievementId);
2742                }
2743                $achievementId = 14;
2744                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2745                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2746                    ClassRegistry::init('AchievementStatus')->create();
2747                    ClassRegistry::init('AchievementStatus')->save($as);
2748                    array_push($updated, $achievementId);
2749                }
2750                $achievementId = 24;
2751                if ($acS['AchievementCondition']['value'] < 15 && !isset($existingAs[$achievementId])) {
2752                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2753                    ClassRegistry::init('AchievementStatus')->create();
2754                    ClassRegistry::init('AchievementStatus')->save($as);
2755                    array_push($updated, $achievementId);
2756                }
2757                $achievementId = 25;
2758                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2759                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2760                    ClassRegistry::init('AchievementStatus')->create();
2761                    ClassRegistry::init('AchievementStatus')->save($as);
2762                    array_push($updated, $achievementId);
2763                }
2764                $achievementId = 26;
2765                if ($acS['AchievementCondition']['value'] < 5 && !isset($existingAs[$achievementId])) {
2766                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2767                    ClassRegistry::init('AchievementStatus')->create();
2768                    ClassRegistry::init('AchievementStatus')->save($as);
2769                    array_push($updated, $achievementId);
2770                }
2771            } elseif ($s['Set']['difficulty'] >= 1300 && $s['Set']['difficulty'] < 1500) {
2772                $achievementId = 15;
2773                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2774                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2775                    ClassRegistry::init('AchievementStatus')->create();
2776                    ClassRegistry::init('AchievementStatus')->save($as);
2777                    array_push($updated, $achievementId);
2778                }
2779                $achievementId = 16;
2780                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2781                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2782                    ClassRegistry::init('AchievementStatus')->create();
2783                    ClassRegistry::init('AchievementStatus')->save($as);
2784                    array_push($updated, $achievementId);
2785                }
2786                $achievementId = 17;
2787                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2788                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2789                    ClassRegistry::init('AchievementStatus')->create();
2790                    ClassRegistry::init('AchievementStatus')->save($as);
2791                    array_push($updated, $achievementId);
2792                }
2793                $achievementId = 27;
2794                if ($acS['AchievementCondition']['value'] < 18 && !isset($existingAs[$achievementId])) {
2795                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2796                    ClassRegistry::init('AchievementStatus')->create();
2797                    ClassRegistry::init('AchievementStatus')->save($as);
2798                    array_push($updated, $achievementId);
2799                }
2800                $achievementId = 28;
2801                if ($acS['AchievementCondition']['value'] < 13 && !isset($existingAs[$achievementId])) {
2802                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2803                    ClassRegistry::init('AchievementStatus')->create();
2804                    ClassRegistry::init('AchievementStatus')->save($as);
2805                    array_push($updated, $achievementId);
2806                }
2807                $achievementId = 29;
2808                if ($acS['AchievementCondition']['value'] < 8 && !isset($existingAs[$achievementId])) {
2809                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2810                    ClassRegistry::init('AchievementStatus')->create();
2811                    ClassRegistry::init('AchievementStatus')->save($as);
2812                    array_push($updated, $achievementId);
2813                }
2814            } elseif ($s['Set']['difficulty'] >= 1500 && $s['Set']['difficulty'] < 1700) {
2815                $achievementId = 18;
2816                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2817                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2818                    ClassRegistry::init('AchievementStatus')->create();
2819                    ClassRegistry::init('AchievementStatus')->save($as);
2820                    array_push($updated, $achievementId);
2821                }
2822                $achievementId = 19;
2823                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2824                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2825                    ClassRegistry::init('AchievementStatus')->create();
2826                    ClassRegistry::init('AchievementStatus')->save($as);
2827                    array_push($updated, $achievementId);
2828                }
2829                $achievementId = 20;
2830                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2831                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2832                    ClassRegistry::init('AchievementStatus')->create();
2833                    ClassRegistry::init('AchievementStatus')->save($as);
2834                    array_push($updated, $achievementId);
2835                }
2836                $achievementId = 30;
2837                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2838                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2839                    ClassRegistry::init('AchievementStatus')->create();
2840                    ClassRegistry::init('AchievementStatus')->save($as);
2841                    array_push($updated, $achievementId);
2842                }
2843                $achievementId = 31;
2844                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2845                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2846                    ClassRegistry::init('AchievementStatus')->create();
2847                    ClassRegistry::init('AchievementStatus')->save($as);
2848                    array_push($updated, $achievementId);
2849                }
2850                $achievementId = 32;
2851                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2852                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2853                    ClassRegistry::init('AchievementStatus')->create();
2854                    ClassRegistry::init('AchievementStatus')->save($as);
2855                    array_push($updated, $achievementId);
2856                }
2857            } else {
2858                $achievementId = 21;
2859                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2860                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2861                    ClassRegistry::init('AchievementStatus')->create();
2862                    ClassRegistry::init('AchievementStatus')->save($as);
2863                    array_push($updated, $achievementId);
2864                }
2865                $achievementId = 22;
2866                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2867                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2868                    ClassRegistry::init('AchievementStatus')->create();
2869                    ClassRegistry::init('AchievementStatus')->save($as);
2870                    array_push($updated, $achievementId);
2871                }
2872                $achievementId = 23;
2873                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2874                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2875                    ClassRegistry::init('AchievementStatus')->create();
2876                    ClassRegistry::init('AchievementStatus')->save($as);
2877                    array_push($updated, $achievementId);
2878                }
2879                $achievementId = 33;
2880                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2881                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2882                    ClassRegistry::init('AchievementStatus')->create();
2883                    ClassRegistry::init('AchievementStatus')->save($as);
2884                    array_push($updated, $achievementId);
2885                }
2886                $achievementId = 34;
2887                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2888                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2889                    ClassRegistry::init('AchievementStatus')->create();
2890                    ClassRegistry::init('AchievementStatus')->save($as);
2891                    array_push($updated, $achievementId);
2892                }
2893                $achievementId = 35;
2894                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2895                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2896                    ClassRegistry::init('AchievementStatus')->create();
2897                    ClassRegistry::init('AchievementStatus')->save($as);
2898                    array_push($updated, $achievementId);
2899                }
2900            }
2901            $achievementId = 46;
2902            if ($acA['AchievementCondition']['value'] >= 100) {
2903                $ac100 = ClassRegistry::init('AchievementCondition')->find('all', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => '%', 'value >=' => 100]]);
2904                if (!$ac100) {
2905                    $ac100 = [];
2906                }
2907                $ac100counter = 0;
2908                $ac100Count = count($ac100);
2909                for ($j = 0; $j < $ac100Count; $j++) {
2910                    if (count(TsumegoUtil::collectTsumegosFromSet($ac100[$j]['AchievementCondition']['set_id'])) >= 100) {
2911                        $ac100counter++;
2912                    }
2913                }
2914                $as100 = ClassRegistry::init('AchievementStatus')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'achievement_id' => $achievementId]]);
2915                if ($as100 == null) {
2916                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2917                    $as['AchievementStatus']['value'] = 1;
2918                    ClassRegistry::init('AchievementStatus')->create();
2919                    ClassRegistry::init('AchievementStatus')->save($as);
2920                    array_push($updated, $achievementId);
2921                } elseif ($as100['AchievementStatus']['value'] != $ac100counter) {
2922                    $as100['AchievementStatus']['value'] = $ac100counter;
2923                    ClassRegistry::init('AchievementStatus')->save($as100);
2924                    array_push($updated, $achievementId);
2925                }
2926            }
2927        }
2928        $updatedCount = count($updated);
2929        for ($i = 0; $i < $updatedCount; $i++) {
2930            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2931            $updated[$i] = [];
2932            $updated[$i][0] = $a['Achievement']['name'];
2933            $updated[$i][1] = $a['Achievement']['description'];
2934            $updated[$i][2] = $a['Achievement']['image'];
2935            $updated[$i][3] = $a['Achievement']['color'];
2936            $updated[$i][4] = $a['Achievement']['xp'];
2937            $updated[$i][5] = $a['Achievement']['id'];
2938        }
2939
2940        return $updated;
2941    }
2942
2943    public static function getXPJump($lvl = null): int {
2944        if ($lvl >= 102) {
2945            return 0;
2946        }
2947        if ($lvl == 101) {
2948            return 1150;
2949        }
2950        if ($lvl == 100) {
2951            return 50000;
2952        }
2953        if ($lvl >= 70) {
2954            return 150;
2955        }
2956        if ($lvl >= 40) {
2957            return 100;
2958        }
2959        if ($lvl >= 20) {
2960            return 50;
2961        }
2962        if ($lvl >= 12) {
2963            return 25;
2964        }
2965
2966        return 10;
2967    }
2968
2969    public static function updateXP($userID, $achievementData): void {
2970        $xpBonus = 0;
2971        $aCount = count($achievementData);
2972        for ($i = 0; $i < $aCount; $i++) {
2973            $xpBonus += $achievementData[$i][4];
2974        }
2975        $u = ClassRegistry::init('User')->findById($userID);
2976        $jumps = [];
2977        $xStart = 40;
2978
2979        for ($i = 1; $i < 102; $i++) {
2980            if ($i == 101) {
2981                $j = 1150;
2982            } elseif ($i == 100) {
2983                $j = 50000;
2984            } elseif ($i >= 70) {
2985                $j = 150;
2986            } elseif ($i >= 40) {
2987                $j = 100;
2988            } elseif ($i >= 20) {
2989                $j = 50;
2990            } elseif ($i >= 12) {
2991                $j = 25;
2992            } else {
2993                $j = 10;
2994            }
2995            $xStart += $j;
2996            $jumps[$i] = $xStart;
2997        }
2998        $next = 0;
2999        $uLevel = $u['User']['level'];
3000        $uXp = $u['User']['xp'];
3001
3002        if ($uLevel < 101) {
3003            $currentJump = $jumps[$uLevel];
3004        } else {
3005            $currentJump = 60000;
3006        }
3007
3008        $firstJump = $currentJump;
3009
3010        if ($uXp + $xpBonus >= $currentJump) {
3011            $next = $uXp + $xpBonus - $currentJump;
3012            $uLevel++;
3013            if ($uLevel < 101) {
3014                $currentJump = $jumps[$uLevel];
3015            } else {
3016                $currentJump = 60000;
3017            }
3018        }
3019        while ($next >= $currentJump) {
3020            $next = $next - $currentJump;
3021            $uLevel++;
3022            if ($uLevel < 101) {
3023                $currentJump = $jumps[$uLevel];
3024            } else {
3025                $currentJump = 60000;
3026            }
3027        }
3028
3029        $u['User']['level'] = $uLevel;
3030        if ($uXp + $xpBonus < $firstJump) {
3031            $u['User']['xp'] += $xpBonus;
3032        } else {
3033            $u['User']['xp'] = $next;
3034        }
3035        $u['User']['nextlvl'] = $currentJump;
3036
3037        ClassRegistry::init('User')->save($u);
3038    }
3039
3040    public static function getPartitionRange($amountRemaining, $collectionSize, $partition) {
3041        if ($collectionSize > 0) {
3042            $amountPartitions = ceil($amountRemaining / $collectionSize);
3043        } else {
3044            return ['0', $collectionSize - 1];
3045        }
3046        if ($collectionSize > 0 && $amountRemaining % $collectionSize == 0) {
3047            return [ $partition * $collectionSize,  $partition * $collectionSize + $collectionSize - 1];
3048        }
3049        $amountCounter = 0;
3050        $amountFrom = 0;
3051        $amountTo = $collectionSize - 1;
3052        while ($amountRemaining > $collectionSize) {
3053            if ($partition == $amountCounter) {
3054                break;
3055            }
3056            $amountRemaining -= $collectionSize;
3057            $amountCounter++;
3058            $amountFrom += $collectionSize;
3059            $amountTo += $collectionSize;
3060        }
3061        $amountTo = $amountFrom + $collectionSize - 1;
3062        if ($partition >= $amountPartitions - 1) {
3063            $amountTo = $amountFrom + $amountRemaining - 1;
3064        }
3065        $a = [];
3066        $a[0] = $amountFrom;
3067        $a[1] = $amountTo;
3068
3069        return $a;
3070    }
3071
3072    /**
3073     * @param int $uid User ID
3074     * @return void
3075     */
3076    protected function handleSearchSettings($uid) {
3077        $this->loadModel('UserContribution');
3078        $uc = $this->UserContribution->find('first', ['conditions' => ['user_id' => $uid]]);
3079        if ($uc == null) {
3080            $uc = [];
3081            $uc['UserContribution']['user_id'] = $uid;
3082            $uc['UserContribution']['added_tag'] = 0;
3083            $uc['UserContribution']['created_tag'] = 0;
3084            $uc['UserContribution']['made_proposal'] = 0;
3085            $uc['UserContribution']['reviewed'] = 0;
3086            $uc['UserContribution']['score'] = 0;
3087            $this->UserContribution->create();
3088            $this->UserContribution->save($uc);
3089        }
3090        new TsumegoFilters();
3091    }
3092
3093    protected function signIn(array $user): void {
3094        Auth::init($user);
3095        $vs = $this->TsumegoStatus->find('first', ['conditions' => ['user_id' => $user['User']['id']], 'order' => 'created DESC']);
3096        if ($vs) {
3097            $this->Session->write('lastVisit', $vs['TsumegoStatus']['tsumego_id']);
3098        }
3099        $this->Session->write('texture', $user['User']['texture']);
3100        $this->Session->write('check1', $user['User']['id']);
3101    }
3102
3103    public function beforeFilter(): void {
3104        $this->loadModel('User');
3105        $this->loadModel('Activate');
3106        $this->loadModel('Tsumego');
3107        $this->loadModel('TsumegoRatingAttempt');
3108        $this->loadModel('Set');
3109        $this->loadModel('TimeModeAttempt');
3110        $this->loadModel('TsumegoStatus');
3111        $this->loadModel('Comment');
3112        $this->loadModel('UserBoard');
3113        $this->loadModel('TsumegoAttempt');
3114        $this->loadModel('AdminActivity');
3115        $this->loadModel('Achievement');
3116        $this->loadModel('AchievementStatus');
3117        $this->loadModel('AchievementCondition');
3118        $this->loadModel('SetConnection');
3119        $this->loadModel('Tag');
3120        $this->loadModel('TagName');
3121        $this->loadModel('Favorite');
3122
3123        Auth::init();
3124        $this->TimeMode->init();
3125
3126        $highscoreLink = 'highscore';
3127        $lightDark = 'light';
3128        $resetCookies = false;
3129        $levelBar = 1;
3130        $lastProfileLeft = 1;
3131        $lastProfileRight = 2;
3132        $hasFavs = false;
3133
3134        if (Auth::isLoggedIn()) {
3135            if (isset($_COOKIE['addTag']) && $_COOKIE['addTag'] != 0 && $this->Session->read('page') != 'set') {
3136                $newAddTag = explode('-', $_COOKIE['addTag']);
3137                $tagId = $newAddTag[0];
3138                $newTagName = $this->TagName->find('first', ['conditions' => ['name' => str_replace($tagId . '-', '', $_COOKIE['addTag'])]]);
3139                if ($newTagName) {
3140                    $saveTag = [];
3141                    $saveTag['Tag']['tag_name_id'] = $newTagName['TagName']['id'];
3142                    $saveTag['Tag']['tsumego_id'] = $tagId;
3143                    $saveTag['Tag']['user_id'] = Auth::getUserID();
3144                    $saveTag['Tag']['approved'] = 0;
3145                    $this->Tag->save($saveTag);
3146                }
3147                $this->set('removeCookie', 'addTag');
3148            }
3149            if (isset($_COOKIE['z_sess']) && $_COOKIE['z_sess'] != 0
3150            && strlen($_COOKIE['z_sess']) > 5) {
3151                Auth::getUser()['_sessid'] = $_COOKIE['z_sess'];
3152                Auth::saveUser();
3153            }
3154            if (Auth::getUser()['lastHighscore'] == 1) {
3155                $highscoreLink = 'highscore';
3156            } elseif (Auth::getUser()['lastHighscore'] == 2) {
3157                $highscoreLink = 'rating';
3158            } elseif (Auth::getUser()['lastHighscore'] == 3) {
3159                $highscoreLink = 'leaderboard';
3160            } elseif (Auth::getUser()['lastHighscore'] == 4) {
3161                $highscoreLink = 'highscore3';
3162            }
3163
3164            if (isset($_COOKIE['lastMode']) && $_COOKIE['lastMode'] != 0) {
3165                Auth::getUser()['lastMode'] = $_COOKIE['lastMode'];
3166                Auth::saveUser();
3167            }
3168            if (isset($_COOKIE['sound']) && $_COOKIE['sound'] != '0') {
3169                Auth::getUser()['sound'] = $_COOKIE['sound'];
3170                Auth::saveUser();
3171                unset($_COOKIE['sound']);
3172            }
3173            $this->set('ac', true);
3174            $this->set('user', Auth::getUser());
3175        }
3176
3177        if (isset($_COOKIE['lightDark']) && $_COOKIE['lightDark'] != '0') {
3178            $lightDark = $_COOKIE['lightDark'];
3179            if (Auth::isLoggedIn()) {
3180                // Convert string to integer for database storage
3181                $lightDarkInt = ($lightDark === 'light') ? 0 : 2;
3182                Auth::getUser()['lastLight'] = $lightDarkInt;
3183            }
3184        } elseif (Auth::isLoggedIn()) {
3185            if (Auth::getUser()['lastLight'] == 0
3186            || Auth::getUser()['lastLight'] == 1) {
3187                $lightDark = 'light';
3188            } else {
3189                $lightDark = 'dark';
3190            }
3191        }
3192
3193        if (Auth::isLoggedIn()) {
3194            $this->handleSearchSettings(Auth::getUserID());
3195            if (isset($_COOKIE['levelBar']) && $_COOKIE['levelBar'] != '0') {
3196                $levelBar = $_COOKIE['levelBar'];
3197                Auth::getUser()['levelBar'] = $levelBar;
3198            } elseif (Auth::getUser()['levelBar'] == 0
3199          || Auth::getUser()['levelBar'] == 'level') {
3200                $levelBar = 1;
3201            } else {
3202                $levelBar = 2;
3203            }
3204
3205            if (isset($_COOKIE['lastProfileLeft']) && $_COOKIE['lastProfileLeft'] != '0') {
3206                $lastProfileLeft = $_COOKIE['lastProfileLeft'];
3207                Auth::getUser()['lastProfileLeft'] = $lastProfileLeft;
3208            } else {
3209                $lastProfileLeft = Auth::getUser()['lastProfileLeft'];
3210                if ($lastProfileLeft == 0) {
3211                    $lastProfileLeft = 1;
3212                }
3213            }
3214            if (isset($_COOKIE['lastProfileRight']) && $_COOKIE['lastProfileRight'] != '0') {
3215                $lastProfileRight = $_COOKIE['lastProfileRight'];
3216                Auth::getUser()['lastProfileRight'] = $lastProfileRight;
3217            } else {
3218                $lastProfileRight = Auth::getUser()['lastProfileRight'];
3219                if ($lastProfileRight == 0) {
3220                    $lastProfileRight = 1;
3221                }
3222            }
3223        }
3224        $mode = 1;
3225        if (isset($_COOKIE['mode']) && $_COOKIE['mode'] != '0') {
3226            if ($_COOKIE['mode'] == 1) {
3227                $mode = 1;
3228            } else {
3229                $mode = 2;
3230            }
3231        }
3232
3233        if (Auth::isLoggedIn() && Auth::getUser()['mode'] == 2) {
3234            $mode = 2;
3235        }
3236
3237        if ($_COOKIE['sprint'] != 1) {
3238            $this->updateSprintCondition();
3239        }
3240        $correctSolveAttempt = false;
3241
3242        if (Auth::isLoggedIn()) {
3243            if (isset($_COOKIE['revelation']) && $_COOKIE['revelation'] != 0) {
3244                Auth::getUser()['revelation'] -= 1;
3245            }
3246
3247            if (!$this->request->is('ajax')) {
3248                $this->PlayResultProcessor->checkPreviousPlay($this->TimeMode);
3249            }
3250
3251            if (isset($_COOKIE['noScore']) && isset($_COOKIE['noPreId'])) {
3252                if ($_COOKIE['noScore'] != '0' && $_COOKIE['noPreId'] != '0') {
3253                    //$previosTsumegoX = $this->Tsumego->findById($_COOKIE['noPreId']);
3254                    //$previosTsumegoXsc = $this->SetConnection->find('first', array('conditions' => array('tsumego_id' => $_COOKIE['noPreId'])));
3255                    //$scoreArrX = explode('-', $this->decrypt($_COOKIE['noScore']));
3256
3257                    $utPreX = $this->TsumegoStatus->find('first', ['conditions' => ['tsumego_id' => $_COOKIE['noPreId'], 'user_id' => Auth::getUserID()]]);
3258                    if ($utPreX == null) {
3259                        $utPreX['TsumegoStatus'] = [];
3260                        $utPreX['TsumegoStatus']['user_id'] = Auth::getUserID();
3261                        $utPreX['TsumegoStatus']['tsumego_id'] = $_COOKIE['noPreId'];
3262                    }
3263                    if ($utPreX['TsumegoStatus']['status'] == 'W') {
3264                        $utPreX['TsumegoStatus']['status'] = 'C';
3265                    } else {
3266                        $utPreX['TsumegoStatus']['status'] = 'S';
3267                    }
3268                    $utPreX['TsumegoStatus']['created'] = date('Y-m-d H:i:s');
3269                    //$this->TsumegoStatus->save($utPreX);
3270                    //$sessionUts = $this->Session->read('loggedInUser.uts');
3271                    /*if (!$sessionUts) {
3272                    $sessionUts = [];
3273                    }
3274                    $sessionUts[$utPreX['TsumegoStatus']['tsumego_id']] = $utPreX['TsumegoStatus']['status'];
3275                    $this->Session->write('loggedInUser.uts', $sessionUts);*/
3276                }
3277            }
3278        }
3279        $boardNames = [];
3280        $enabledBoards = [];
3281        $boardPositions = [];
3282
3283        $boardNames[1] = 'Pine';
3284        $boardNames[2] = 'Ash';
3285        $boardNames[3] = 'Maple';
3286        $boardNames[4] = 'Shin Kaya';
3287        $boardNames[5] = 'Birch';
3288        $boardNames[6] = 'Wenge';
3289        $boardNames[7] = 'Walnut';
3290        $boardNames[8] = 'Mahogany';
3291        $boardNames[9] = 'Blackwood';
3292        $boardNames[10] = 'Marble 1';
3293        $boardNames[11] = 'Marble 2';
3294        $boardNames[12] = 'Marble 3';
3295        $boardNames[13] = 'Tibet Spruce';
3296        $boardNames[14] = 'Marble 4';
3297        $boardNames[15] = 'Marble 5';
3298        $boardNames[16] = 'Quarry 1';
3299        $boardNames[17] = 'Flowers';
3300        $boardNames[18] = 'Nova';
3301        $boardNames[19] = 'Spring';
3302        $boardNames[20] = 'Moon';
3303        $boardNames[21] = 'Apex';
3304        $boardNames[22] = 'Gold 1';
3305        $boardNames[23] = 'Amber';
3306        $boardNames[24] = 'Marble 6';
3307        $boardNames[25] = 'Marble 7';
3308        $boardNames[26] = 'Marble 8';
3309        $boardNames[27] = 'Marble 9';
3310        $boardNames[28] = 'Marble 10';
3311        $boardNames[29] = 'Jade';
3312        $boardNames[30] = 'Quarry 2';
3313        $boardNames[31] = 'Black Bricks';
3314        $boardNames[32] = 'Wallpaper 1';
3315        $boardNames[33] = 'Wallpaper 2';
3316        $boardNames[34] = 'Gold & Gray';
3317        $boardNames[35] = 'Gold & Pink';
3318        $boardNames[36] = 'Veil';
3319        $boardNames[37] = 'Tiles';
3320        $boardNames[38] = 'Mars';
3321        $boardNames[39] = 'Pink Cloud';
3322        $boardNames[40] = 'Reptile';
3323        $boardNames[41] = 'Mezmerizing';
3324        $boardNames[42] = 'Magenta Sky';
3325        $boardNames[43] = 'Tsumego Hero';
3326        $boardNames[44] = 'Pretty';
3327        $boardNames[45] = 'Hunting';
3328        $boardNames[46] = 'Haunted';
3329        $boardNames[47] = 'Carnage';
3330        $boardNames[48] = 'Blind Spot';
3331        $boardNames[49] = 'Giants';
3332        $boardNames[50] = 'Gems';
3333        $boardNames[51] = 'Grandmaster';
3334        $boardPositions[1] = [1, 'texture1', 'black34.png', 'white34.png'];
3335        $boardPositions[2] = [2, 'texture2', 'black34.png', 'white34.png'];
3336        $boardPositions[3] = [3, 'texture3', 'black34.png', 'white34.png'];
3337        $boardPositions[4] = [4, 'texture4', 'black.png', 'white.png'];
3338        $boardPositions[5] = [5, 'texture5', 'black34.png', 'white34.png'];
3339        $boardPositions[6] = [6, 'texture6', 'black.png', 'white.png'];
3340        $boardPositions[7] = [7, 'texture7', 'black34.png', 'white34.png'];
3341        $boardPositions[8] = [8, 'texture8', 'black.png', 'white.png'];
3342        $boardPositions[9] = [9, 'texture9', 'black.png', 'white.png'];
3343        $boardPositions[10] = [10, 'texture10', 'black34.png', 'white34.png'];
3344        $boardPositions[11] = [11, 'texture11', 'black34.png', 'white34.png'];
3345        $boardPositions[12] = [12, 'texture12', 'black34.png', 'white34.png'];
3346        $boardPositions[13] = [13, 'texture13', 'black34.png', 'white34.png'];
3347        $boardPositions[14] = [14, 'texture14', 'black34.png', 'white34.png'];
3348        $boardPositions[15] = [15, 'texture15', 'black.png', 'white.png'];
3349        $boardPositions[16] = [16, 'texture16', 'black34.png', 'white34.png'];
3350        $boardPositions[17] = [17, 'texture17', 'black34.png', 'white34.png'];
3351        $boardPositions[18] = [18, 'texture18', 'black.png', 'white.png'];
3352        $boardPositions[19] = [19, 'texture19', 'black34.png', 'white34.png'];
3353        $boardPositions[20] = [20, 'texture20', 'black34.png', 'white34.png'];
3354        $boardPositions[21] = [33, 'texture33', 'black34.png', 'white34.png'];
3355        $boardPositions[22] = [21, 'texture21', 'black.png', 'whiteKo.png'];
3356        $boardPositions[23] = [22, 'texture22', 'black34.png', 'white34.png'];
3357        $boardPositions[24] = [34, 'texture34', 'black.png', 'white.png'];
3358        $boardPositions[25] = [35, 'texture35', 'black34.png', 'white34.png'];
3359        $boardPositions[26] = [36, 'texture36', 'black.png', 'white.png'];
3360        $boardPositions[27] = [37, 'texture37', 'black34.png', 'white34.png'];
3361        $boardPositions[28] = [38, 'texture38', 'black38.png', 'white34.png'];
3362        $boardPositions[29] = [39, 'texture39', 'black.png', 'white.png'];
3363        $boardPositions[30] = [40, 'texture40', 'black34.png', 'white34.png'];
3364        $boardPositions[31] = [41, 'texture41', 'black34.png', 'white34.png'];
3365        $boardPositions[32] = [42, 'texture42', 'black34.png', 'white42.png'];
3366        $boardPositions[33] = [43, 'texture43', 'black34.png', 'white42.png'];
3367        $boardPositions[34] = [44, 'texture44', 'black34.png', 'white34.png'];
3368        $boardPositions[35] = [45, 'texture45', 'black34.png', 'white42.png'];
3369        $boardPositions[36] = [47, 'texture47', 'black34.png', 'white34.png'];
3370        $boardPositions[37] = [48, 'texture48', 'black34.png', 'white34.png'];
3371        $boardPositions[38] = [49, 'texture49', 'black.png', 'white.png'];
3372        $boardPositions[39] = [50, 'texture50', 'black34.png', 'white34.png'];
3373        $boardPositions[40] = [51, 'texture51', 'black34.png', 'white34.png'];
3374        $boardPositions[41] = [52, 'texture52', 'black34.png', 'white34.png'];
3375        $boardPositions[42] = [53, 'texture53', 'black34.png', 'white34.png'];
3376        $boardPositions[43] = [54, 'texture54', 'black54.png', 'white54.png'];
3377        $boardPositions[44] = [23, 'texture23', 'black.png', 'whiteFlower.png'];
3378        $boardPositions[45] = [24, 'texture24', 'black24.png', 'white24.png'];
3379        $boardPositions[46] = [25, 'texture25', 'blackGhost.png', 'white.png'];
3380        $boardPositions[47] = [26, 'texture26', 'blackInvis.png', 'whiteCarnage.png'];
3381        $boardPositions[48] = [27, 'texture27', 'black27.png', 'white27.png'];
3382        $boardPositions[49] = [28, 'texture28', 'blackGiant.png', 'whiteKo.png'];
3383        $boardPositions[50] = [29, 'texture29', 'blackKo.png', 'whiteKo.png'];
3384        $boardPositions[51] = [30, 'texture55', 'blackGalaxy.png', 'whiteGalaxy.png'];
3385
3386        $boardCount = 51;
3387
3388        if ($this->Session->check('texture') || (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0')) {
3389            $splitCookie = [];
3390            if (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0') {
3391                $splitCookie = str_split($_COOKIE['texture']);
3392                $textureCookies = $_COOKIE['texture'];
3393                Auth::getUser()['texture'] = $this->Session->read('texture');
3394                $this->Session->write('texture', $_COOKIE['texture']);
3395                $this->set('textureCookies', $textureCookies);
3396            } else {
3397                if (Auth::isLoggedIn()) {
3398                    $this->Session->write('texture', Auth::getUser()['texture']);
3399                }
3400                $textureCookies = $this->Session->read('texture');
3401                $splitTextureCookies = str_split($textureCookies);
3402                $splitTextureCookiesCount = count($splitTextureCookies);
3403                for ($i = 0; $i < $splitTextureCookiesCount; $i++) {
3404                    if ($splitTextureCookies[$i] == 2) {
3405                        $enabledBoards[$i + 1] = 'checked';
3406                    } else {
3407                        $enabledBoards[$i + 1] = '';
3408                    }
3409                }
3410            }
3411
3412            $splitCookieCount = count($splitCookie);
3413            for ($i = 0; $i < $splitCookieCount; $i++) {
3414                if ($splitCookie[$i] == 2) {
3415                    $enabledBoards[$i + 1] = 'checked';
3416                } else {
3417                    $enabledBoards[$i + 1] = '';
3418                }
3419            }
3420            if (Auth::isLoggedIn()) {
3421                Auth::saveUser();
3422            }
3423        }
3424
3425        if (!$this->Session->check('texture')) {
3426            $this->Session->write('texture', '222222221111111111111111111111111111111111111111111');
3427            $enabledBoards[1] = 'checked';
3428            $enabledBoards[2] = 'checked';
3429            $enabledBoards[3] = 'checked';
3430            $enabledBoards[4] = 'checked';
3431            $enabledBoards[5] = 'checked';
3432            $enabledBoards[6] = 'checked';
3433            $enabledBoards[7] = 'checked';
3434            $enabledBoards[8] = 'checked';
3435            $enabledBoards[9] = '';
3436            $enabledBoards[10] = '';
3437            $enabledBoards[11] = '';
3438            $enabledBoards[12] = '';
3439            $enabledBoards[13] = '';
3440            $enabledBoards[14] = '';
3441            $enabledBoards[15] = '';
3442            $enabledBoards[16] = '';
3443            $enabledBoards[17] = '';
3444            $enabledBoards[18] = '';
3445            $enabledBoards[19] = '';
3446            $enabledBoards[20] = '';
3447            $enabledBoards[21] = '';
3448            $enabledBoards[22] = '';
3449            $enabledBoards[23] = '';
3450            $enabledBoards[24] = '';
3451            $enabledBoards[25] = '';
3452            $enabledBoards[26] = '';
3453            $enabledBoards[27] = '';
3454            $enabledBoards[28] = '';
3455            $enabledBoards[29] = '';
3456            $enabledBoards[30] = '';
3457            $enabledBoards[31] = '';
3458            $enabledBoards[32] = '';
3459            $enabledBoards[33] = '';
3460            $enabledBoards[34] = '';
3461            $enabledBoards[35] = '';
3462            $enabledBoards[36] = '';
3463            $enabledBoards[37] = '';
3464            $enabledBoards[38] = '';
3465            $enabledBoards[39] = '';
3466            $enabledBoards[40] = '';
3467            $enabledBoards[41] = '';
3468            $enabledBoards[42] = '';
3469            $enabledBoards[43] = '';
3470            $enabledBoards[44] = '';
3471            $enabledBoards[45] = '';
3472            $enabledBoards[46] = '';
3473            $enabledBoards[47] = '';
3474            $enabledBoards[48] = '';
3475            $enabledBoards[49] = '';
3476            $enabledBoards[50] = '';
3477            $enabledBoards[51] = '';
3478        }
3479        $achievementUpdate = [];
3480        if ($this->Session->check('initialLoading')) {
3481            $achievementUpdate1 = $this->checkLevelAchievements();
3482            $achievementUpdate2 = $this->checkProblemNumberAchievements();
3483            $achievementUpdate3 = $this->checkRatingAchievements();
3484            $achievementUpdate4 = $this->checkTimeModeAchievements();
3485            $achievementUpdate5 = $this->checkDanSolveAchievements();
3486            $achievementUpdate = array_merge(
3487                $achievementUpdate1 ?: [],
3488                $achievementUpdate2 ?: [],
3489                $achievementUpdate3 ?: [],
3490                $achievementUpdate4 ?: [],
3491                $achievementUpdate5 ?: []
3492            );
3493            $this->Session->delete('initialLoading');
3494        }
3495
3496        if (count($achievementUpdate) > 0) {
3497            $this->updateXP(Auth::getUserID(), $achievementUpdate);
3498        }
3499
3500        $nextDay = new DateTime('tomorrow');
3501        if (Auth::isLoggedIn()) {
3502            Auth::getUser()['name'] = $this->checkPicture(Auth::getUser());
3503            $this->set('user', Auth::getUser());
3504        }
3505        $this->set('mode', $mode);
3506        $this->set('nextDay', $nextDay->format('m/d/Y'));
3507        $this->set('boardNames', $boardNames);
3508        $this->set('enabledBoards', $enabledBoards);
3509        $this->set('boardPositions', $boardPositions);
3510        $this->set('highscoreLink', $highscoreLink);
3511        $this->set('achievementUpdate', $achievementUpdate);
3512        $this->set('lightDark', $lightDark);
3513        $this->set('levelBar', $levelBar);
3514        $this->set('lastProfileLeft', $lastProfileLeft);
3515        $this->set('lastProfileRight', $lastProfileRight);
3516        $this->set('resetCookies', $resetCookies);
3517        $this->set('hasFavs', $hasFavs);
3518    }
3519
3520    public function afterFilter() {}
3521}